ES6差

2016-10-19 3 views
0

次関数ES6差

module.exports = utils.Backbone.View.extend({ 
    handler:() => { 
     console.log(this); 
    } 
}); 

module.exports = utils.Backbone.View.extend({ 
    handler() { 
     console.log(this); 
    } 
}); 

なぜ最初のケースthis === windowでの違いは何ですか?

+1

これは違いです。矢印機能が 'this'をバインドしません –

答えて

0

矢印関数は独自のコンテキストを作成しないため、thisは囲むコンテキストの元の値を持ちます。

あなたのケースでは、囲むコンテキストはグローバルコンテキストなので、矢印機能のthiswindowです。一方

const obj = { 
    handler:() => { 
    // `this` points to the context outside of this function, 
    // which is the global context so `this === window` 
    } 
} 

は、定期的な機能のためのコンテキストは動的であり、そのような機能は、オブジェクトのメソッド、メソッドの所有オブジェクトへthis点として定義されている場合。

const obj = { 
    handler() { 
    // `this` points to `obj` as its context, `this === obj` 
    } 
} 

上記の構文では、ES6 method shorthandが使用されます。機能的には次のものと同等です。

const obj = { 
    handler: function handler() { 
    // `this` points to `obj` as its context, `this === obj` 
    } 
} 
+1

完全にクリア、ありがとう! – francesca