[英]ES6 Arrow functions vs ES5: how to know which function to bind `this` to when using ES5 non-arrow function
我正在閱讀這篇關於使用 ES6 箭頭函數的文章。 它給出了以下示例,您必須在其中使用bind(this)
,然后是帶有箭頭函數的相應代碼。
var obj = {
id: 42,
counter: function counter() {
setTimeout(function() {
console.log(this.id);
}.bind(this), 1000);
}
};
它說In the ES5 example, .bind(this) is required to help pass the this context into the function
。
我想知道的:為什么你使用bind(this)
和setTimeout
的回調而不是counter
function? 即為什么上面的代碼不是這樣的:
var obj = {
id: 42,
counter: function counter() {
setTimeout(function() {
console.log(this.id);
}, 1000);
}.bind(this);
};
為什么你使用
bind(this)
和setTimeout
的回調而不是計數器 function?
因為counter
function (它的工作方式類似於obj
對象的方法)已經具有正確的this
,因為您將其obj.counter()
,因此它通過將其稱為obj.counter()
來獲取this
。 假設您將 counter 稱為obj.counter()
,那么如果您在counter()
function 的第一行執行console.log(this.id)
,它將正確顯示id
值。
但是,您傳遞給setTimeout()
的回調沒有自然的this
值,除非您在回調 function 本身上使用箭頭 function 或.bind()
,因為當setTimeout()
調用您的回調時,它不會設置特定的this
值(它只是調用您的回調作為普通函數),因此this
值變為默認值。 這意味着如果運行嚴格模式或全局 object 如果在setTimeout()
回調內以松散-goosey 模式運行, this
將是undefined
的。
調用 function 時,請參閱此處設置this
值的 6 種方式。
我還應該提到,如果你按照你的提議做了這樣的事情:
var obj = {
id: 42,
counter: function counter() {
setTimeout(function() {
console.log(this.id);
}, 1000);
}.bind(this);
};
它不僅對setTimeout()
回調沒有任何幫助,而且還會將this
的錯誤值綁定到counter()
方法。 您將得到this
在var obj
定義之前的任何內容(也稱為this
的詞法值)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.