You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
function list() {
return Array.prototype.slice.call(arguments);
}
var list1 = list(1, 2, 3); // [1, 2, 3]
// Create a function with a preset leading argument
var leadingThirtysevenList = list.bind(undefined, 37);
var list2 = leadingThirtysevenList(); // [37]
var list3 = leadingThirtysevenList(1, 2, 3); // [37, 1, 2, 3]
fakeBind = function (context) {
if (typeof this !== "function") {
throw new Error("Function.prototype.bind - what is trying to be bound is not callable");
}
var slice = Array.prototype.slice,
_args = slice.call(arguments, 1),
self = this,
F = function () {},
bound = function () {
var _inargs = slice.call(arguments);
return self.apply((this instanceof F ? this : context), _args.concat(_inargs));
};
F.prototype = self.prototype;
bound.prototype = new F();
return bound;
}
Function.prototype.bind = Function.prototype.bind || fakeBind;
ES6版实现
Function.prototype.fakeBindES6 = function(context, ...rest) {
if (typeof this !== "function") {
throw new Error("Bind must be called on a function");
}
var self = this;
return function inner(...args) {
if (this instanceof inner) {
// 当返回的内层函数作为构造函数使用,bind 时绑定的 this 失效。
// 即此处直接执行绑定函数,而不使用 apply 对 this 进行绑定
return new self(...rest, ...args);
}
// 当作为普通函数调用,this 指向传入的对象
return self.apply(context, rest.concat(args));
};
};
The text was updated successfully, but these errors were encountered:
bind方法可以用来给一个方法绑定上下文环境对象,以及重新给方法传参数。
bind的另一个简单使用是使一个函数拥有预设的初始参数。我们称为偏函数
由于bind方法在并不是在所有的浏览器上都支持,因此我们考虑自己实现bind方法。
首先我们可以给目标函数指定作用域来简单实现bind
这样实现的bind方法就只能接受一个上下文环境变量的参数,不能同时接受参数。因此我们修改一下。
现在bind可以绑定对象,同时也能在绑定对象时传递参数。
但是bind还有一个特点:
举个例子:
我们可以通过修改函数的返回原型来实现,代码如下:
bound.prototype = this.prototype
这么写的话,修改返回函数原型对象(bound.prototype)的同时把绑定函数的原型对象(this.prototype也同时修改了。因此用匿名函数做中转,this.protptype 就安全了。还有几个小问题的解决:
最终的完整代码如下:
ES6版实现
The text was updated successfully, but these errors were encountered: