0

I'm updating a variable from an outer scope in a nested function,
as this is happening during a init function the outer scope isn't the outermost (window) scope;

var init = function() {

  var x = 'old stuff' ;      

        function butClick() {
          x = 'new stuff' ; 
        }
  console.log(x); //  new stuff

  document.querySelector("btn").addEventListener("click", butClick, false);
}
window.addEventListener( 'DOMContentLoaded', init, false);

in order to save it in the init-function scope I'm omitting the var keyword and as expected the new value of the variable bubbles up and updates;

but the result of console.log('x' in window ) is false,
isn't the bubbling supposed to get to the window scope?

4

1 に答える 1

2

x関数内で宣言されてinitいるため、xその関数内 (またはその内部のもの) はグローバルに解決されません。


これとは別に、質問のコードのコメント:

console.log(x) //  new stuff

...xその時点で「新しいもの」になることを意味します。それはしません。どこにも電話 していないので、元の「古いもの」の値があります。butClickx

ある時点で呼び出すと、ローカルのに更新されます。グローバルを作成または更新しません。butClickxinit


イベントハンドラーとしての更新設定について: 「新しいもの」であるべきだとbutClick示唆するコメントはまだ間違っています。行が実行xされている時点で、値は「古いもの」です。後で、誰かがボタンをクリックすると、によって更新されますが、遡及的に行を再実行することはありません。console.logxxbutClickconsole.log

しかし、クリックに応答して呼び出された場合でも、グローバルではなくwithinをbutClick更新しています。変数のスコープは、関数がどこから呼び出されるかによって決定されるのではなく、語彙的に決定されます。xinit

于 2015-01-29T11:16:13.620 に答える