彻底理解call
var obj = {
name: "pig"
}
function showName() {
return this.name;
}
console.log(showName.call(obj));
var name = "pig1";
var obj = {
name: "pig2",
fn: function showName() {
return this.name;
}
}
console.log(obj.fn());
// 把当前执行函数的this指向传入的对象obj,等于在对象obj中调用当前函数
// 创建obj中的假当前函数fn=Symbol(),通过obj[fn] = this将当前函数转给他
// 执行假函数并返回,返回前删除创建的假函数
Function.prototype.myCall = function (obj = window, ...args) {
const fn = Symbol();
obj[fn] = this;
const newFunc = obj[fn](...args);
delete obj[fn];
return newFunc;
}
Function.prototype.myApply = function (target, args) { // 区别就是这里第二个参数直接就是个数组
target = target || window
const symbolKey = Symbol()
target[symbolKey] = this
const res = target[symbolKey](...args) // args本身是个数组,所以我们需要解构后一个个传入函数中
delete target[symbolKey] // 执行完借用的函数后,删除掉,留着过年吗?
return res
}
# 手动实现call()函数
// c1.showAge.call(c2, 18);
// c2就是context,c1里的this给了c2添加的属性fn上,调用c1.showAge就是this.showAge就是context[fn].showAge
Function.prototype.myCall = function (context = window, ...args) {
const fn = Symbol(); // 创建一个独一无二的symbol:fn
context[fn] = this; //将fn作为属性添加到context上
console.log("this:", this);
const result = context[fn](...args);
delete context[fn]; //调用函数后即删除该Symbol属性
return result;
};
function Class1() {
this.name = "class1";
this.showName = function () {
console.log(this.name);
};
this.showAge = function (age) {
console.log(age);
};
}
function Class2() {
this.name = "class2";
}
var c1 = new Class1();
var c2 = new Class2();
c1.showName.myCall(c2); // class2