繁体   English   中英

绑定与调用/应用的setTimeout

[英]setTimeout for bind vs call/apply

我正在查看一些代码,发现这是绑定和调用/应用之间的区别。

var colt = {
    firstName: "rohit",
    sayHI: function() {
        setTimeout(function(){
            console.log("hi" + this.firstName)
        }, 3000)
    }
}
  • 在这里,当this.firstName运行时,由于该函数已经执行,因此它开始引用全局上下文。 那么我们该如何解决呢?
  • 我们可以使用Call and Apply,但是Call and Apply会立即调用该函数。
  • 因此,我们使用bind。 绑定方法返回函数定义

然后他们提到了这个例子

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM