简体   繁体   English

绑定与调用/应用的setTimeout

[英]setTimeout for bind vs call/apply

I was going through some code where I spotted this as a difference between bind and call/apply. 我正在查看一些代码,发现这是绑定和调用/应用之间的区别。

var colt = {
    firstName: "rohit",
    sayHI: function() {
        setTimeout(function(){
            console.log("hi" + this.firstName)
        }, 3000)
    }
}
  • Here when this.firstName runs, it starts referring to the global context since the function is already executed. 在这里,当this.firstName运行时,由于该函数已经执行,因此它开始引用全局上下文。 So how do we solve them? 那么我们该如何解决呢?
  • We can use Call and Apply, but Call and Apply evokes the function right away. 我们可以使用Call and Apply,但是Call and Apply会立即调用该函数。
  • Hence we use bind. 因此,我们使用bind。 Bind method returns function definition 绑定方法返回函数定义

And then they mentioned this example 然后他们提到了这个例子

 var colt = {
        firstName: "rohit",
        sayHI: function() {
            setTimeout(function(){
                console.log("hi" + this.firstName)
            }.bind(this), 3000)
        }
    } //this would be evoked when the function runs

For some reason, I am unable to make sense out of it. 由于某些原因,我无法理解。 Can someone please help me understand this? 有人可以帮我理解吗?

Edited: 编辑:

  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