这是MDN上关于bind原理的一块代码,原网页链接:
var ArrayPrototypeSlice = Array.prototype.slice;
Function.prototype.bind = function(otherThis) {
var baseArgs= ArrayPrototypeSlice.call(arguments, 1),
baseArgsLength = baseArgs.length,
fToBind = this,
fNOP = function() {},
fBound = function() {
baseArgs.length = baseArgsLength; // reset to default base arguments
baseArgs.push.apply(baseArgs, arguments);
return fToBind.apply(
// {↓此行标记↓}
fNOP.prototype.isPrototypeOf(this) ? this : otherThis, baseArgs
);
};
if (this.prototype) {
// Function.prototype doesn't have a prototype property
fNOP.prototype = this.prototype;
}
fBound.prototype = new fNOP();
return fBound;
};
在最后,fBound需要将调用bind的函数的prototype继承为自己的prototype,为什么不直接:
fBound.prototype = this.prototype;
而是绕了一大圈弄了个新函数:
var fNOP = function() {},
if (this.prototype) {
fNOP.prototype = this.prototype;
}
fBound.prototype = new fNOP();
这么做的目的是什么呢?
by the way,在第一段的标记代码中:
// {此行标记}
fNOP.prototype.isPrototypeOf(this) ? this : otherThis, baseArgs
为什么使用fNop
来做instance
检测而不使用fBound
,这二者有什么区别吗?
劳驾答疑,不胜感激。
第一个是为了解决引用类型问题。(借用构造函数进行继承)
第二个你要用fNop做继承难道拿fBound做检测吗?