我有一个关于EcmaScript-5 Function.prototype.bind实现的非常有趣的问题。通常当你使用绑定,你做这种方式:Function.prototype.bind
var myFunction = function() {
alert(this);
}.bind(123);
// will alert 123
myFunction();
好了,这很酷,但什么是假设我们这样做的时候会发生什么?
// rebind binded function
myFunction = myFunction.bind('foobar');
// will alert... 123!
myFunction();
据我所知,这是在Function.prototype.bind是如何实现的(https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind)方面完全合乎逻辑的行为。但在现实生活中,这完全是无用的行为,不是吗?问题是:它是缺陷还是功能?如果这是一个错误,为什么它没有提到?如果这是一项功能,那么为什么Google Chrome与原生“绑定”实现的行为方式完全相同?
为了使它更清楚,在我看来,你会更有意义,这里是实现Function.prototype.bind的代码片段一点点不同:
if (!Function.prototype.bind) {
Function.prototype.bind = function() {
var funcObj = this;
var original = funcObj;
var extraArgs = Array.prototype.slice.call(arguments);
var thisObj = extraArgs.shift();
var func = function() {
var thatObj = thisObj;
return original.apply(thatObj, extraArgs.concat(
Array.prototype.slice.call(
arguments, extraArgs.length
)
));
};
func.bind = function() {
var args = Array.prototype.slice.call(arguments);
return Function.prototype.bind.apply(funcObj, args);
}
return func;
};
}
所以现在试试这个:
// rebind binded function
myFunction = myFunction.bind('foobar');
// will alert... "foobar"
myFunction();
在我看来,取代“本”更有意义......
所以你们认为是什么呢?
这是一个功能。如果你可以重写它,它不会真的“受限制”,会吗?详细信息可以在规范中找到:http://ecma262-5.com/ELS5_HTML.htm#Section_15.3.4.5 –
肯定,但如果是,那么什么是确定的功能已经被绑定到方式什么?或者为什么它在试图重新绑定时不会抛出任何异常?问题在于,如果你不知道函数是否被绑定,或者你处理了它的第一个副本,那么调试非常困难。昨天发生了这样的事情,我花了将近一天的时间来找出问题的根源...... – Ruslan
好吧,无论如何,似乎没有人会回答这个问题,所以如果别人会有同样的问题,我创建了一个workaroud,你可以在这里找到:http://www.angrycoding.com/2011/09/to-bind-or-not-to-bind-that-is-in.html – Ruslan