2017-08-18 3 views
0

私もJavaでその無名関数を読んで、それがabove.Iは、次の例で混乱しています意味を囲む関数内で新しいスコープが導入されていますは匿名関数が動的スコープですか?ラムダ式は、ブロックlocal.Doesあるのに対し、

var timer = { 
    seconds: 0, 
    start() { 
     setInterval(() => { 
      this.seconds++ 
     }, 1000) 
    } 
} 
// When an item is searched, it starts from the anonymous function 
// and this doesn't mean the same as parent this. 
// This means that we can access this .seconds by first going to 
// its enclosing function in the arrow expression. 
timer.start() 

setTimeout(function() { 
    console.log(timer.seconds) 
}, 3500) 

ここでこれを。それが匿名関数であれば、囲み関数内でこれの新しいスコープが導入されます。そうでしょうか? Static (Lexical) Scoping vs Dynamic Scoping (Pseudocode)

+0

'this 'キーワードは、あなたが探しているものであれば"スコープ "と呼ばれません。 – Bergi

+0

「無名関数」と「ラムダ式」とはどういう意味ですか?関数式と矢印関数はどちらも匿名である可能性があります。 – Bergi

+0

親切に私に何かを説明してください –

答えて

0

ここでの違いはthisです。矢印関数はthisの値を変更しませんが、functionキーワードで作成した関数は変更します。あなたは上記の持っているコードと次のコードの間に差がある理由です

:このコードで

var timer = { 
    seconds: 0, 
    start() { 
     setInterval(function(){ 
      this.seconds++ 
     }, 1000) 
    } 
} 
// When an item is searched, it starts from the anonymous function 
// and this doesn't mean the same as parent this. 
// This means that we can access this .seconds by first going to 
// its enclosing function in the arrow expression. 
timer.start() 

setTimeout(function() { 
    console.log(timer.seconds) 
}, 3500) 

は、function(){は、それ自体にthisの値を上書きし、その変数何秒はもうありません。

伝統的な匿名関数と矢印関数の間にスコープ(関数にアクセスできる変数)の違いはなく、従来の匿名関数では新しいthisが作成され、矢印関数では使用できません。

関連する問題