[英]setTimeout for bind vs call/apply
我正在查看一些代碼,發現這是綁定和調用/應用之間的區別。
var colt = {
firstName: "rohit",
sayHI: function() {
setTimeout(function(){
console.log("hi" + this.firstName)
}, 3000)
}
}
然后他們提到了這個例子
var colt = {
firstName: "rohit",
sayHI: function() {
setTimeout(function(){
console.log("hi" + this.firstName)
}.bind(this), 3000)
}
} //this would be evoked when the function runs
由於某些原因,我無法理解。 有人可以幫我理解嗎?
編輯:
let colt = { firstName: "rohit", sayHI: function() { setTimeout( /* 1. Create a new function. */ function() { /* 3. The 'this' = colt object. */ console.log("hi" + this.firstName) } /* 2. Make a copy of the function and set the inside 'this' keyword with a colt object. And when you call 'this' inside the function is this colt object. */ .bind(this), 500); } }.sayHI(); //this would be evoked when the function runs
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.