二维码

JavaScript this 关键字

JavaScript this 关键字


1
2
3
4
5
6
7
8
const person = {  
  firstName: "John",
  lastName : "Doe",
  id       : 5566,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};


this什么?

在 JavaScript 中,this关键字指的是一个对象

哪个对象取决于调用(使用或调用)的方式。

this关键字引用不同的对象,具体取决于它的使用方式:

在对象方法中,this对象
单独,this全局对象
在函数中,this引用全局对象
在函数中,在严格模式下,thisundefined
在事件中,this 指接收事件的元素
call()apply()bind()等方法可以将this引用到任何对象。

注意

this不是一个变量。这是一个关键词。不能更改this的值。


this 在方法中

在对象方法中使用时,this对象

在此页顶部的示例中,this引用 person 对象。

因为 fullName 方法是 person 对象的方法。

1
2
3
fullName : function() {  
  return this.firstName + " " + this.lastName;
}


this独自

单独使用时,this全局对象

因为this是在全局范围内运行的。

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

1
let x = this;

严格模式下,单独使用时,this全局对象

1
2
"use strict";  
let x = this;


this in a Function(默认)

在函数中,全局对象this的缺省绑定。

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

1
2
3
function myFunction() {  
  return this;
}


this in a 函数 (Strict)

JavaScript 严格模式不允许默认绑定。

因此,当在函数中使用时,在严格模式下,thisundefined

1
2
3
4
"use strict";  
function myFunction() {
  return this;
}


this 在事件处理程序中

在 HTML 事件处理程序中,this指接收 事件:

1
2
3
<button onclick="this.style.display='none'">  
  Click to Remove Me!
</button>


对象方法绑定

在这些示例中,this是 person 对象

1
2
3
4
5
6
7
8
const person = {  
  firstName  : "John",
  lastName   : "Doe",
  id         : 5566,
  myFunction : function() {
    return this;
  }
};

1
2
3
4
5
6
7
8
const person = {  
  firstName: "John",
  lastName : "Doe",
  id       : 5566,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};

即 this.firstName 是 this(person 对象)的 firstName 属性。


显式函数绑定

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

它们都可用于调用一个对象方法,并将另一个对象作为参数。

另请参见:

[函数 call() 方法]

[函数 apply() 方法]

[函数 bind() 方法]

下面的示例调用 person1.fullName并将person2作为参数,thisperson2, 即使 fullNameperson1的方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
const person1 = {  
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
}

const person2 = {
  firstName:"John",
  lastName: "Doe",
}

// Return "John Doe":
person1.fullName.call(person2);


函数借用

bind()使用该方法,一个对象可以从另一个对象借用方法。

此示例创建 2 个对象(person 和 member)。

成员对象从person对象借用fullname方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const person = {  
  firstName:"John",
  lastName: "Doe",
  fullName: function () {
    return this.firstName + " " + this.lastName;
  }
}

const member = {
  firstName:"Hege",
  lastName: "Nilsen",
}

let fullName = person.fullName.bind(member);

This优先级

确定this指的是哪个对象;使用以下优先顺序。

优先 对象
1 bind()
2 apply()和 call()
3 Object 方法
4 Global scope

this是否使用 bind() 调用函数?

this是否使用 apply() 调用函数?

this是否使用 call() 调用函数?

this在对象函数(方法)中吗?

this位于全局范围内的函数中。