簡體   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