我正在學習函數式編程和node.js,當使用Function.prototype.apply
和.bind
時,我遇到了這個奇怪的問題。函數參數不一定是對象嗎?
function Spy(target, method) {
var obj = {count: 0};
var original = target[method]
target[method] = function(){//no specified arguments
obj.count++
original.apply(this, arguments)//only arguments property passed
}
return obj;
}
module.exports = Spy
此代碼正常工作,它成功偵測了target.method
。
//same code here
target[method] = function (args){//args specified
obj.count++
original.apply(this, args)//and passed here
}
//same code here
此代碼,但是,其實不然。它給出了一個錯誤信息:TypeError: CreateListFromArrayLike called on non-object
。
然後最大的驚喜是,這種方法工作得很好。
//same code here
target[method] = function (args){
obj.count++
original.bind(this, args)
}
//same code here
那麼爲什麼我確切地得到這個錯誤呢?是否因爲函數參數不一定是對象?或者是因爲申請比綁定更嚴格?
嗯,是的,['apply'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply)和['bind'](https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind)有很不同的描述。 'apply'將一個數組或一個['arguments'對象](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments)作爲第二個參數 - 如果你不'它通過一個,它抱怨。 – Bergi
非常不清楚。首先,作品/不工作代碼片段是相同的(除非我失去了一些東西)。其次,'bind'不會調用該函數,因此很難相信「有效」。 – Amit
@非常抱歉,我要編輯,所以更明顯。 –