- 名词解释:call() 方法使用一个指定的 this 值和单独给出的一个或多个参数来调用一个函数。
- 原生方法:Function.prototype.call()
- 先看一下原生方法的调用
let obj = {
name: "jay chou",
getName: function () {
console.log(this.name);
},
getNameAge(age) {
console.log(this.name + " " + age);
},
};
let obj2 = {
name: "Jolin Tsai",
};
obj.getName.call(obj2);
obj.getNameAge.call(obj2, 40);
- 自己实现一个myCall方法
let obj = {
name: "jay chou",
getName: function () {
console.log(this.name);
},
getNameAge(age) {
console.log(this.name + " " + age);
},
};
let obj2 = {
name: "Jolin Tsai",
};
Function.prototype.myCall = function (context, ...arg) {
const _this =
typeof context == "object" ? (context ? context : window) : window;
const key = Symbol();
_this[key] = this;
_this[key](...arg);
delete _this[key];
};
obj.getName.myCall(obj2);
obj.getNameAge.myCall(obj2, 40);
obj.getNameAge.myCall(1, 40);
obj.getNameAge.myCall("1234", 40);
obj.getNameAge.myCall(["1234"], 40);
obj.getNameAge.myCall(new Date(), 40);
obj.getNameAge.myCall(new RegExp("/BB/"), 40);
function Person(name) {
this.name = name;
console.log("姓名:" + this.name);
}
Person.myCall(null, "jay");
let person = new Person("jolin");
obj.getName.myCall(person);