在讨论这个问题之前,我们先看一下在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]]都被重载,实际指向原函数
本文深入探讨了ES5中bind函数的内部实现机制,解释了其如何通过原型链优化性能,以及如何正确使用bind来创建可绑定this的函数副本。文章详细分析了bind函数的工作原理,并提供了实例演示。
1874

被折叠的 条评论
为什么被折叠?



