JavaScript 中 call()、apply()、bind() 的用法

在JavaScript 中,call、apply 和 bind 是 Function 对象自带的三个方法,这三个方法的主要作用是改变函数调用过程中的 this 指向

1 apply


Function.apply(obj,args)

apply方法接收两个参数

  1. obj:这个对象将代替Function类里this对象

  2. args:这个是数组,它将作为参数传给Function(args-->arguments)

不带第一个参数


var person = {
    fullName: function() {
        return this.firstName + " " + this.lastName;
    }
}
var person1 = {
    firstName: "Bill",
    lastName: "Gates",
}
person.fullName.apply(person1);  // 将返回 "Bill Gates"

带全部参数


var person = {
  fullName: function(city, country) {
    return this.firstName + " " + this.lastName + "," + city + "," + country;
  }
}
var person1 = {
  firstName:"John",
  lastName: "Doe"
}
person.fullName.apply(person1, ["Oslo", "Norway"]);


2 call


Function.call(obj[,params...])

call方法接收两个参数

  1. obj:这个对象将代替Function类里this对象

  2. args:这个是一个参数列表

不带第一个参数


var person = {
    fullName: function() {
        return this.firstName + " " + this.lastName;
    }
}
var person1 = {
    firstName:"Bill",
    lastName: "Gates",
}
var person2 = {
    firstName:"Steve",
    lastName: "Jobs",
}
person.fullName.call(person1);  // 将返回 "Bill Gates"

带全部参数

var person = {
  fullName: function(city, country) {
    return this.firstName + " " + this.lastName + "," + city + "," + country;
  }
}
var person1 = {
  firstName:"Bill",
  lastName: "Gates"
}
person.fullName.call(person1, "Seattle", "USA");

3 bind

Function.bind(obj[,params...])
bind是ES5 新增的一个方法,它的传参和call类似,也是接收两个参数。

  1. obj:这个对象将代替Function类里this对象

  2. args:这个是一个参数列表

不带第一个参数


var person = {
    fullName: function() {
        return this.firstName + " " + this.lastName;
    }
}
var person1 = {
    firstName:"Bill",
    lastName: "Gates",
}
var person2 = {
    firstName:"Steve",
    lastName: "Jobs",
}
person.fullName.call(person1)();  // 将返回 "Bill Gates"

带全部参数


var person = {
  fullName: function(city, country) {
    return this.firstName + " " + this.lastName + "," + city + "," + country;
  }
}
var person1 = {
  firstName:"Bill",
  lastName: "Gates"
}
person.fullName.call(person1, "Seattle", "USA")();

可以从上面看出,使用方法基本和call一致,只是后面多了(),其实是bind不会立即执行对应的函数,只是返回对函数的引用。那为什么要引入bind呢,是因为call和apply会自动执行目标函数,从而无法绑定在事件上,因为事件是我们手动触发的,而bind不会自动执行目标函数。

上一篇:vue---watch、computed和methods之间的区别


下一篇:vue中计算属性和侦听属性