// 实现 call
Function.prototype.myCall = function (context = window, ...args) {
const key = Symbol();
// 避免原有属性被覆盖
context[key] = this;
// 通过隐式绑定的方式调用函数
const result = context[key](...args);
// 不改变原对象
delete context[key];
//返回函数调用的返回值
return result;
};
// 实现 apply
Function.prototype.myApply = function (context = window, args = []) {
const key = Symbol();
// 避免原有属性被覆盖
context[key] = this;
// 通过隐式绑定的方式调用函数
const result = context[key](...args);
// 不改变原对象
delete context[key];
//返回函数调用的返回值
return result;
};
// 实现 bind
Function.prototype.myBind = function (context = window, ...args) {
const fn = this
return function newFn(...newFnArgs) {
if (this instanceof newFn) {
return fn.apply(this, [...args, ...newFnArgs])
}
return fn.apply(context, [...args, ...newFnArgs])
}
};
function Func(a) {
this.a = a;
this.logA = function (arg1, arg2, arg2) {
console.log(this.a, arg1, arg2)
}
}
const obj = {
a: 1,
logA(arg1, arg2) {
console.log(this.a, arg1, arg2)
},
getA(arg1, arg2) {
return this.a + arg1 + arg2;
}
}
window.a = 2
const obj2 = {
a: 3
}
// const newFunc = Func.myBind(this, 2);
// const func = new newFunc(3);
// func.logA(4)
// const newObj = obj.bind
Function.prototype.newCall = function (context = window, ...args) {
const key = Symbol();
context[key] = this;
const result = context[key](...args)
delete context[key];
return result;
}
Function.prototype.newApply = function (context = window, args = []) {
const key = Symbol();
context[key] = this;
const result = context[key](...args)
delete context[key];
return result;
}
Function.prototype.newBind = function (context = window, ...args) {
const fn = this;
function newFn(...newArgs) {
if (context instanceof newFn) {
context.apply(context, [...args, ...newArgs])
} else {
context.apply(fn, [...args, ...newArgs])
}
}
}
console