手写 bind 函数
Function.prototype.bind2 = function(context) {
const self = this;
const args1 = [].slice.call(arguments, 1);
const newFn = function() {
const args2 = args1.concat([].slice.call(arguments));
self.apply(this instanceof self ? this : context, args2);
};
newFn.prototype = self.prototype;
return newFn;
};
function a(x = 0, y = 0) {
console.log({ x, y });
}
const b = {};
a.bind(b)(1, 2);
a.bind2(b)(1, 2);
function c(name, hobby) {
this.name = name;
this.hobby = hobby;
}
const d = {};
const fn = c.bind(d, "Mike", "Eat");
console.log(new fn());
const fn2 = c.bind2(d, "Mike", "Eat");
console.log(new fn2());
Function.prototype.bind2 = function(context) {
const _this = this;
const args = [...arguments].slice(1);
return function F() {
if (this instanceof F) {
return new _this(...args, ...arguments);
}
return _this.apply(context, args.concat(...arguments));
};
};
function a(x = 0, y = 0) {
console.log({ x, y });
}
const b = {};
a.bind(b)(1, 2);
a.bind2(b)(1, 2);
function c(name, hobby) {
this.name = name;
this.hobby = hobby;
}
const d = {};
const fn = c.bind(d);
console.log(new fn( "Mike", "Eat"));
const fn2 = c.bind2(d);
console.log(new fn2("Mike", "Eat"));