Function.prototype.myCall = function(context, ...arg) {
context = context || window;
const temp = Symbol('fn');
context[temp] = this;
const res = context[temp](...arg);
delete context[temp]
return res;
}
Function.prototype.myApply = function(context, arg) {
context = context || window;
const temp = Symbol('fn');
context[temp] = this;
const res = context[temp](...(arg || []));
delete context[temp]
return res;
}
Function.prototype.myBind = function(context, ...arg) {
context = context || window;
const fn = this;
return function Fn(...arg1) {
const that = this instanceof Fn ? this : context;
return fn.apply(that, [...arg, ...arg1]);
}
}
var a = 1;
function test(b,c,d) {
this.aaa = 1;
console.log(this.a, b,c,d);
}
test();
test.myCall({ a: 'call' }, 1,2);
test.myApply({ a: 'apply' });
var testBind = test.bind({ a: 'bind' }, 1);
testBind(3);
const newObj = new testBind('--2--')
console.log(newObj);