let Person = {
name: "zhangsan",
say(age, className) {
console.log(`your name ${this.name}, age ${age}, className ${className}`);
}
};
let Person1 = {
name: "lisi"
};
// your name lisi, age 12, className class1
Person.say.myCall(Person1, 12, "class1");
let Person = {
name: "zhangsan",
say(age, className) {
console.log(
`say your name ${this.name}, age ${age}, className ${className}`
);
},
speak([age, className]) {
console.log(
`speak your name ${this.name}, age ${age}, className ${className}`
);
}
};
let Person1 = {
name: "lisi"
};
// speak your name lisi, age 20, className class2
Person.speak.myApply(Person1, [20, "class2"]);
区别
call() 和 apply()的区别在于,call()方法接受的是若干个参数的列表,而 apply()方法接受的是一个包含多个参数的数组
使用场景
数组中最大值
验证是否是数组
可以通过 toString() 来获取每个对象的类型,但是不同对象的 toString()有不同的实现,所以通过 Object.prototype.toString() 来检测,需要以 call() / apply() 的形式来调用,传递要检查的对象作为第一个参数。
手写 call
看上去是不是挺简单的,下面来试下这个方法
手写 apply