JavaScript改变this指向的三种方法

发布时间 2023-12-30 21:31:23作者: 奇迹会出现

JavaScript call() 方法

它可以用来调用所有者对象作为参数的方法。通过 call(),您能够使用属于另一个对象的方法。
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"

 上面的例子中,它为什么最后的输出是"Bill Gates"呢?因为call()方法改变了this的指向,把原本this指向为person变成指向为person1了

同时,call()方法可以接受参数:

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");//Bill Gates,Seatle,USA

 

JavaScript apply() 方法

apply() 方法与 call() 方法非常相似

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

 

call() 和 apply() 之间的区别

1.call() 方法分别接受参数

2.apply() 方法接受数组形式的参数。

apply() 方法接受数组中的参数:

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

bind()方法

bind() 方法创建一个新函数,当调用该新函数时,它会调用原始函数并将其 this 关键字设置为给定的值,同时,还可以传入一系列指定的参数,这些参数会插入到调用新函数时传入的参数的前面。

const module = {
  x: 42,
  getX: function () {
    return this.x;
  },
};

const unboundGetX = module.getX;
console.log(unboundGetX()); // The function gets invoked at the global scope
// Expected output: undefined

const boundGetX = unboundGetX.bind(module);
console.log(boundGetX());
// Expected output: 42