簡體   English   中英

Function.prototype.bind.apply()無法按預期工作

[英]Function.prototype.bind.apply() doesn't work as expected

我有一個函數myfunc並希望bindbind到特定的this參數和其他參數bind為單個數組,而不是參數列表(因為我將參數列表作為函數的參數,執行此代碼)。 為此,我使用apply on bind如下:

var myfunc = function(arg1, arg2){
    alert("this = " + this + ", arg1 = " + arg1 + ", arg2 = " + arg2);
}
var bindedMyfunc = myfunc.bind.apply("mythis", ["param1", "param2"]);
bindedMufunc();

這導致Uncaught TypeError: Bind must be called on a function

我究竟做錯了什么? 你能否詳細解釋一下,當我運行這段代碼時會發生什么,導致現實似乎與我的看法相矛盾?

答案摘要:似乎bind自身有自己的this參數,它是函數,它被調用。 例如,當你說myfunc.bind(args)bindthismyfunc

通過調用apply on bind我錯誤地將bind的命名分配給了“mythis”,這不是一個函數,並且不能在它上面調用bind

所以,解決方案是使用

myfunc.bind.apply(myfunc, ["mythis"].concat(["param1", "param2"]))

此外,如果你想立即調用綁定的myfunc,你可以說:

myfunc.apply.bind(myfunc)("mythis", ["param1", "param2"])

但這不足以解決我的問題,因為我需要將綁定函數作為參數傳遞給addEventListener

謝謝你的幫助,伙計們!

您應該使用該函數作為apply方法的第一個參數。 myfunc.bind的使用不會將函數與調用相關聯,它具有Function.prototype.bind的效果,您也可以使用它。

bind方法的第一個參數( thisArg )應該是數組中的第一個項目。

var bindedMyfunc = Function.prototype.bind.apply(myfunc, ["mythis", "param1", "param2"]);

似乎綁定本身有自己的這個參數,它是函數,它被調用。 例如,當你說myfunc.bind(args)bindthismyfunc

究竟。 如果要應用bind ,則必須將其應用於函數(第一個參數),並將bind參數(包括預期的this值)作為數組(第二個參數)傳遞:

(Function.prototype.bind).apply(myfunc, ["mythis", "param1", "param2"])
// which is equivalent to
myfunc.bind("mythis", "param1", "param2")
(…args) => myfunc.call("mythis", "param1", "param2", …args) // ES6 syntax

但是,還有另一種方法可以解決您的問題:綁定apply函數,並部分應用建議的apply參數:

(Function.prototype.apply).bind(myfunc, "mythis", ["param1", "param2"])
// which is equivalent to
(…args) => myfunc.apply("mythis", ["param1", "param2"], …args) // ES6 syntax

也許你想bind apply而不是apply bind

var bindedMyfunc = Function.prototype.apply.bind(myfunc);
bindedMyfunc('obj', [1, 2]); // this = obj, arg1 = 1, arg2 = 2

我經常使用這種模式使hasOwnProperty檢查更短而不會被遮蔽;

var has = Function.prototype.call.bind(Object.hasOwnProperty);
has({foo:1}, 'foo'); // true
has({foo:1}, 'bar'); // false

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM