手写call apply bind方法
相同点:改变this指向
不同点:传参列表不同
call方法
Function.prototype.myCall = function (ctx, ...args) {
const self = this;
ctx = ctx === undefined || ctx === null ? globalThis : Object(ctx)
const key = Symbol();
Object.defineProperty(ctx, {
value: self,
enumerable: false,
})
const result = ctx[key](...args);
delete ctx[key];
return result;
};
apply方法
- fn.apply(this, [a, b,..])
Function.prototype.myApply = function (ctx, params = []) {
if (!Array.isArray(params)) {
throw "参数必须为数组";
}
const self = this;
ctx = ctx === undefined || ctx === null ? globalThis : Object(ctx)
const key = Symbol();
Object.defineProperty(ctx, {
value: self,
enumerable: false,
})
const result = ctx[key](...params);
delete ctx[key];
return result;
};
bind方法
- let res = fn.bind(this, a, b,..)
- res(c, d,...)
Function.prototype.myBind = function (ctx, ...args) {
const self = this;
return function (...args2) {
ctx = ctx === undefined || ctx === null ? globalThis : Object(ctx)
const key = Symbol();
Object.defineProperty(ctx, {
value: self,
enumerable: false,
})
const result = ctx[key](...args.concat(...args2));
delete ctx[key];
return result;
};
};