在讨论这个问题之前,我们先看一下在es5出现内置的bind函数之前,是怎么模拟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 && oThis
? this
: oThis || window,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
实际上一个绑定函数没有prototype属性,
Thus,
a bound function does not have a prototype
property
or the [[Code]]
(the
function body code),[[FormalParameters]]
(the
list of formal parameter names), and [[Scope]]
(a
parent lexical or variable environment) internal properties.
如果返回绑定函数的prototype属性,则会输出目标函数的prototype
这么做的好处是优化性能,绑定函数本身并不是一个完整的函数,而是原函数的中间代理。
绑定函数的[[Call]]
, [[Construct]]
and [[HasInstance]]都被重载,实际指向原函数