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

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

1 applyapp

Function.apply(obj,args)

apply方法接收两个参数ide

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

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

不带第一个参数this

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

带所有参数code

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对象ip

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

不带第一个参数ci

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不会自动执行目标函数。

相关文章
相关标签/搜索