[英]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.