在讨论这个问题之前,我们先看一下在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]]都被重载,实际指向原函数
http://dmitrysoshnikov.com/notes/note-1-ecmascript-bound-functions/
本文深入探讨了ES5中bind函数的内部实现方式,解释了如何在不使用内置bind的情况下手动创建绑定函数,并阐述了这种实现方式在性能优化方面的优势。通过分析bind函数的构造过程,理解其如何避免不必要的原型属性和代码冗余,从而提高执行效率。
1875

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



