关于This学习

105 阅读2分钟

要想理解什么事This,首先要明白函数调用的来龙去脉。

函数是什么

  • 函数的本质是什么,函数的本质是对象的方法;
  • 下面创建了一个带有三个属性的对象(firstName,LastName,fullName);
  • 示例:
var person = {
    firstName:"Bill",
    lastName: "Gates",
    fullName: function () {
        return this.firstName + " " + this.lastName;
    }
}
person.fullName();		// 将返回 "Bill Gates"
  • 这个fullname用一个函数function()表达出来,函数里面的内容就是 return this.firstName + " " + this.lastName;;
  • 如何让这个函数的结果表达出来,就是调用person.fullName();
  • fullname属性是一个方法,person对象是该对象的拥有者。

JavaScript call() 方法

call() 方法是预定义的 JavaScript 方法。

它可以用来调用所有者对象作为参数的方法。

通过 call(),您能够使用属于另一个对象的方法。

本例调用 person 的 fullName 方法,并用于 person1:

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"

带参数的 call() 方法

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");

This是什么?

JavaScript this 关键词指的是它所属的对象。

它拥有不同的值,具体取决于它的使用位置:

  • 在方法中,this 指的是所有者对象。
  • 单独的情况下,this 指的是全局对象。
  • 在函数中,this 指的是全局对象。
  • 在函数中,严格模式下,this 是 undefined。
  • 在事件中,this 指的是接收事件的元素。

像 call() 和 apply() 这样的方法可以将 this 引用到任何对象。

方法中的this

在对象方法中,this 指的是此方法的“拥有者”。

在本页最上面的例子中,this 指的是 person 对象。

person 对象是 fullName 方法的拥有者。

var person = {
  firstName: "Bill",
  lastName : "Gates",
  id       : 678,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};

单独的 this

在单独使用时,拥有者是全局对象,因此 this 指的是全局对象。

在浏览器窗口中,全局对象是 [object Window]:

var x = this;

全局对象的This

在 JavaScript 函数中,函数的拥有者默认绑定 this。

因此,在函数中,this 指的是全局对象 [object Window]。

function myFunction() {
  return this;
}

显示函数绑定

call() 和 apply() 方法是预定义的 JavaScript 方法。

它们都可以用于将另一个对象作为参数调用对象方法。 在下面的例子中,当使用 person2 作为参数调用 person1.fullName 时,this 将引用 person2,即使它是 person1 的方法:

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