Javascript 函数绑定重写(如何将其绑定到另一个对象)
Javascript function bind override (how to bind it to another object)
有没有办法重新绑定已经通过 Function.prototype.bind 绑定到另一个对象的函数?
var a={};
var b={};
var c=function(){ alert(this===a); };
c(); // alerts false
c=c.bind(a);
c(); // alerts true
c=c.bind(b);
c(); // still alerts true
我知道我可以使用不同的方法并保留 "clean" 绑定函数,但我只是想知道如何重用已绑定的函数。
.bind()
所做的几乎与此相同:
function likeBind(fun, thisValue) {
return function() {
var args = [].slice.call(arguments, 0);
return fun.apply(thisValue, args);
};
}
所以:
c = likeBind(c, a);
给你一个绑定函数。现在,即使您尝试重新绑定,原始绑定函数仍然存在于该闭包中,其值是您最初请求用作 this
的值。闭包内部变量的值只能从闭包内部更改,因此您无法像那样取消绑定绑定函数。你必须从原来的功能重新开始。
所以,没有。
Is there a way to rebind a function that is already bound to another object via Function.prototype.bind?
没有。来自 ES2015 spec 关于 Function.prototype.bind
:
19.2.3.2 Function.prototype.bind ( thisArg , ...args)
[...]
Note 2: If Target is an arrow function or a bound function then the thisArg passed to this method will not be used by subsequent calls to F.
早期版本也是如此。
有没有办法重新绑定已经通过 Function.prototype.bind 绑定到另一个对象的函数?
var a={};
var b={};
var c=function(){ alert(this===a); };
c(); // alerts false
c=c.bind(a);
c(); // alerts true
c=c.bind(b);
c(); // still alerts true
我知道我可以使用不同的方法并保留 "clean" 绑定函数,但我只是想知道如何重用已绑定的函数。
.bind()
所做的几乎与此相同:
function likeBind(fun, thisValue) {
return function() {
var args = [].slice.call(arguments, 0);
return fun.apply(thisValue, args);
};
}
所以:
c = likeBind(c, a);
给你一个绑定函数。现在,即使您尝试重新绑定,原始绑定函数仍然存在于该闭包中,其值是您最初请求用作 this
的值。闭包内部变量的值只能从闭包内部更改,因此您无法像那样取消绑定绑定函数。你必须从原来的功能重新开始。
所以,没有。
Is there a way to rebind a function that is already bound to another object via Function.prototype.bind?
没有。来自 ES2015 spec 关于 Function.prototype.bind
:
19.2.3.2 Function.prototype.bind ( thisArg , ...args)
[...]
Note 2: If Target is an arrow function or a bound function then the thisArg passed to this method will not be used by subsequent calls to F.
早期版本也是如此。