小码农养成记

JavaScript 中的 call、apply、bind 和

2021-10-26  本文已影响0人  F_wind

JavaScript

call :改变 this 指向,第一个参数是新指向的 this,后面是 arguments 参数,接收形式是逗号间隔的参数;
apply:用法与 call 类似,arguments 参数接收形式改为数组;
bind:用法与 call 类似,调用以后返回一个函数引用,如果需要实现 call 效果,则需要在后面加小括号 () ,就可以直接执行了。

例子:

var name = "Tom",
  age = 12;
var userInfo = {
  name: "Jack",
  newAge: this.age,
  get: function (arg1) {
    var that = this;
    return (
      "name:" +
      this.name +
      ",age:" +
      this.age +
      ",from:" +
      arg1 +
      ",to:" +
      arguments[1]
    );
  },
};
console.log(userInfo.name); // Jack
console.log(userInfo.newAge); // undefined
console.log(userInfo.get()); // name:Jack,age:undefined,from:undefined,to:undefined

var user1 = { name: "Lucy", age: 5 };
console.log(userInfo.get.call(user1)); // name:Lucy,age:5,from:undefined,to:undefined
console.log(userInfo.get.apply(user1)); // name:Lucy,age:5,from:undefined,to:undefined
console.log(userInfo.get.bind(user1)()); // name:Lucy,age:5,from:undefined,to:undefined
console.log("#########");
console.log(userInfo.get.call(user1, "US", "china")); // name:Lucy,age:5,from:US,to:china
console.log(userInfo.get.apply(user1, ["US", "china"])); // name:Lucy,age:5,from:US,to:china
console.log(userInfo.get.bind(user1, "US", "china")()); // name:Lucy,age:5,from:US,to:china
上一篇下一篇

猜你喜欢

热点阅读