We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
function-bind.js
module.exports = Function.bind || function bind(that /* , ...args */) { // 判断是否是一个函数 var F = aCallable(this); var Prototype = F.prototype; // 拿到除that之外的函数 var partArgs = arraySlice(arguments, 1); // 返回的函数 var boundFunction = function bound(/* args... */) { // 拼接参数 var args = concat(partArgs, arraySlice(arguments)); // 重点!! // 判断this是否是boundFunction的实例 // 函数bind之后的函数再new出一个实例,这个实例其实是通过,原函数new出的实例,并不会更改this指向 return this instanceof boundFunction ? construct(F, args.length, args) : F.apply(that, args); }; // 继承this函数的原型 if (isObject(Prototype)) boundFunction.prototype = Prototype; return boundFunction; };
var construct = function (C, argsLength, args) { if (!hasOwn(factories, argsLength)) { for (var list = [], i = 0; i < argsLength; i++) list[i] = 'a[' + i + ']'; // 通过Function创建函数 // 创建出的函数为 // ƒ anonymous(C,a // ) { // return new C(a[0],a[1]) // } factories[argsLength] = Function('C,a', 'return new C(' + join(list, ',') + ')'); } return factories[argsLength](C, args); };
例子
function a(){} function b(){} const c=a._bind(b) const d=new c('a','c','d')
d为a函数bind之后的函数new出的实例对象
d
a
bind
new
construct函数返回出的函数为
construct
ƒ anonymous(C,a) { // C是通过boundFunction闭包保存的例子中的a函数 return new C(a[0],a[1],a[2]) }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
bind
function-bind.js
例子
d
为a
函数bind
之后的函数new
出的实例对象construct
函数返回出的函数为The text was updated successfully, but these errors were encountered: