call
Function.prototype.myCall = function (thisArg, ...argArray) {
const _thisArg = thisArg ? Object(thisArg) : {};
const fn = Symbol('fn');
_thisArg[fn] = this;
const res = _thisArg[fn](...argArray);
delete _thisArg[fn];
return res;
};
apply
Function.prototype.myApply = function (thisArg, argArray) {
const _thisArg = thisArg ? Object(thisArg) : {};
const fn = Symbol('fn');
_thisArg[fn] = this;
const res = _thisArg[fn](...argArray);
delete _thisArg[fn];
return res;
};
bind
Function.prototype.myBind = function (thisArg = window, ...argArray) {
const _thisArg = thisArg ? Object(thisArg) : {};
const that = this;
return function proxyFn(...args) {
const fn = Symbol('fn');
_thisArg[fn] = that;
const res = _thisArg[fn](...args, ...argArray);
delete _thisArg[fn];
return res;
};
};
test
const obj = {
name: 'coderxie'
}
function foo(age, height) {
console.log(this.name);
console.log(age);
console.log(height);
}
foo.myCall(obj, 18, 1.88)
foo.myApply(obj, [18, 1.88])
const foo2 = foo.myBind(obj, 18)
foo2(1.88)
1 条评论
?哲理类评语?