对this的理解

120 阅读1分钟

this 代表当前this直属的函数所属的对象。

**1、**在方法中,this 表示该方法所属的对象

var person = {
  firstName: "John",
  lastName : "Doe",
  id: 5566,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};
person.fullName() //John Doe

在对象方法中, this 指向调用它所在方法的对象。

在上面一个实例中,this 表示 person 对象。

fullName 方法所属的对象就是 person。

2、在函数中,this 表示全局对象

function myFunction() {
  return this;
}
myFunction();// Window 严格模式下为undefined

3、在事件中,this 表示接收事件的元素

<button onclick="this.style.display='none'">
点我后我就消失了
</button>

在 HTML 事件句柄中,this 指向了接收事件的 HTML 元素 上面中this指向button元素

4、apply 和 call 允许切换函数执行的上下文环境(context),即 this 绑定的对象,可以将 this 引用到任何对象

var person1 = {
  firstName:"anny",
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
}
var person2 = {
  firstName:"John",
  lastName: "Doe",
}
person1.fullName.call(person2);  // "John Doe"

在上面实例中,当我们使用 person2 作为参数来调用 person1.fullName 方法时, this 将指向 person2, 即便它是 person1 的方法