apply
Function.prototype.myApply = function(context=globalThis,...args){
let key = Symbol('key');
context[key] = this;
let result = context[key](args);
delete context[key];
return result;
}
function f(a,b){
console.log(a+b)
console.log(this.name)
}
let obj={
name:'张三'
}
f.myApply(obj,[1,2])
call
Function.prototype.newCall = function(context=globalThis,...args) {
let key = Symbol('key')
context[key] = this
let result = context[key](...args)
delete context[key]
return result;
}
function f(a,b){
console.log(a+b)
console.log(this.name)
}
let obj={
name:1
}
f.newCall(obj,1,2)
bind
Function.prototype.myBind = function (context, ...outerArgs) {
let self = this
return function F(...innerArgs) {
if(self instanceof F) {
return new self(...outerArgs, ...innerArgs)
}
return self.apply(context, [...outerArgs, ...innerArgs])
}
}