call方法实现
const name = "Marry";
function myCall() {
const arr = Array.from(arguments);
const obj = arr.splice(0,1)[0];
const sym = Symbol('a');
obj[sym] = this;
obj[sym](...arr);
delete obj[sym];
}
let obj = {name: 'jack'};
function per() {
console.log(this.name)
}
Function.prototype.myCall = myCall;
per();
per.myCall(obj);
per.call(obj);
console.log(obj);
apply实现
function myApply() {
const arr = Array.from(arguments);
if (arr[1] && !Array.isArray(arr[i])) {
return new TypeError("The second argument must be an array");
}
const obj = arr[0] || window;
const agu = arr[1] || [];
obj.fn = this;
obj.fn(agu);
delete obj.fn
}
Function.prototype.myApply = myApply;
const obj = {age: 100};
window.age = 200;
function A() {
console.log(this.age)
}
A();
A.myApply(obj)
bind实现(bind有返回)
function myBind() {
let arr = Array.from(arguments);
const obj = arr.splice(0,1)[0] || window;
const sym = Symbol("a");
obj[sym] = this;
console.log(obj);
return function () {
obj[sym](...arr);
}
}
Function.prototype.myBind = myBind;
const obj = {name: "jack"};
const name = "Marry";
function B() {
console.log(this.name);
}
const bind = B.myBind(obj);
B();
bind();