【发布时间】:2012-02-07 05:00:33
【问题描述】:
我正在阅读function definition of bind,但我无法 100% 理解所写的代码:
if (!Function.prototype.bind) {
Function.prototype.bind = function(oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function() {},
fBound = function() {
return fToBind.apply(this instanceof fNOP
? this
: oThis || window,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
具体看不懂fNOP的用途,也不明白为什么需要设置fBound的原型。我也挂断了fToBind.apply 部分(我无法弄清楚这在这种情况下代表什么)。
有人能解释一下这里发生了什么吗?
【问题讨论】:
-
我需要更多伏特加“Smirnoff”来回答这个问题...
-
stage.learn.jquery.com/javascript-101/closures 大约一半,这有什么启示吗?
-
我认为它不会有太大帮助,但供参考:
Function.prototype.bindspecification. -
@Davis 这不是绑定的定义,它是旧浏览器的部分(!)解决方法。
-
请记住,MDN 是一个 wiki,并且可能是错误的。这是代码的来源:developer.mozilla.org/index.php?title=en/JavaScript/Reference/…
标签: javascript logic