2015-03-18 53 views
7

我遇到有這種模式在許多地方的一些代碼:this.someFunction.call的用途是什麼(this,param);

this.someFunction.call(this, param); 

,但在我看來只是一個打字

this.someFunction(param) 

的更詳細的方法的模式有時會出現內部作爲回調提供的功能。它恰好使用Backbone,以防相關。事情是這樣的:

Backbone.View.extend({ 
    // other stuff ... 

    someFunction: function(param) { 
     // ... 
    }, 
    anotherFunction: function() { 
     this.collection.on("some_event", function() { 
      this.someFunction.call(this, param); 
     }); 
    } 
}); 

請問模式實際上有不是this.someFunction(param)或相當於是有人只是擔心關閉不捕獲正確this的影響?

感謝您的任何見解!

+3

*「或者是某人只是緊張的關閉不捕獲正確的'this'」*'this'是函數內部的一個特殊值,不受範圍的影響。 (例外:ES6箭頭功能)。我沒有看到在這裏比通常的函數調用更喜歡'.call'的原因。 – 2015-03-18 22:38:23

+0

兩者都可能是某種編碼慣例。 腳本也經常被混淆。 – kidwon 2015-03-18 22:42:32

+0

請注意,使用call()會增加一些開銷並降低執行速度,這在循環中尤其明顯。代碼實際上可以寫爲:this.collection.on(「some_event」,this.someFunction.bind(this,param));'它提前鎖定_this_,可以比call()更快。儘管取決於骨幹如何使用_this_,您可能需要在另一個函數()中複製綁定值以在當時擁有正確的_this_。 – dandavis 2015-03-18 22:52:37

回答

2

請問模式實際上有不是this.someFunction(param)同等的效果?

不,他們確實是一樣的。假設this.someFunction是一個從Function.prototype繼承.call的函數(但這是挑剔的)。

看起來有人過於謹慎,或者代碼是兩次沒有使用this的東西的遺骸。或者,也許作者知道this-context-in-callbacks issue,但未能正確處理它。

1

我沒有看到任何理由在您提供的代碼中使用這種函數調用方式。這是更好地使用直接函數調用像這樣(如果你需要的參數沒有修改)

this.collection.on("some_event", this.someFunction, this); 

this.collection.on("some_event", function() { 
    this.someFunction(//some modified args) 
}, this); 

讓我提供的.call正確使用的例子。當然u've看到這一點:

Array.prototype.slice.call(arguments, 2); 

作爲arguments不是數組,我們可以「借用」陣列方法與arguments進行操作。如果你嘗試致電slicearguments你會得到一個錯誤