JavaScript 中 call()、apply()、bind() 的用法、相似点及区别对比

89 阅读1分钟
// 例一
let name = 'w', age = 17;
let obj = {
 name'z',
 objAgethis.age,
 myFunfunction() {
   console.log(this.name + "'s age is " + this.age);
}
}
​
obj.objAge;  // undefined
obj.myFun(); // z's age is undefined// 例二
var fav = 'cc';
function shows() {
 console.log(this.fav);
}
shows(); // cc, 若用let则结果是undefined

例一打印中的 this 指向 obj ,例二全局声明的 shows() 函数 thiswindow

call(), apply(), bind() 都是用来重定义 this 这个对象的

let name = 'w', age = 17;
let obj = {
 name'z',
 objAgethis.age,
 myFunfunction() {
   console.log(this.name + "'s age is " + this.age);
}
}
let db = {
 name'd',
 age99
}
obj.myFun.call(db);    // d's age is 99
obj.myFun.apply(db);   // d's age is 99
obj.myFun.bind(db)();  // d's age is 99

bind 方法返回的是一个新的函数,必须调用它才会被执行

对比 call,apply,bind传参情况

let name = 'w', age = 17;
let obj = {
 name'z',
 objAgethis.age,
 myFunfunction(fm, t) {
   console.log(`${this.name}'s age is ${this.age}, he went from ${fm} to ${t}`);
}
}
let db = {
 name'd',
 age99
}
obj.myFun.call(db, 'chengdu''shanghai');      // d's age is 99, he went from chengdu to shanghai
obj.myFun.apply(db, ['chengdu''shanghai']);   // d's age is 99, he went from chengdu to shanghai
obj.myFun.bind(db, 'chengdu''shanghai')();    // d's age is 99, he went from chengdu to shanghai
obj.myFun.bind(db, ['chengdu''shanghai'])();  // d's age is 99, he went from chengdu, shanghai to undefined

call, apply, bind 三个函数第一个参数都是 this 的指向对象,第二个参数就有差别了:

  • call 参数是直接放进去的,后面n个参数全部用逗号分隔,直接放后面
  • apply 所有参数都必须放到一个数组里传进去
  • bind 除了返回的是函数,参数与call一样

三者的参数不限定是string类型,允许是各种类型,包括函数、object等