Javascript 简明教程
JavaScript - this Keyword
What is 'this' keyword?
在 JavaScript 中,“ this ”关键字包含对该对象引用的地址。它表示函数或当前代码的上下文。它用于访问当前对象的属性和方法。
In JavaScript, the 'this' keyword contains the reference to the object. It represents the context of the function or current code. It is used to access the properties and methods of the current object.
当在函数中使用此关键字时,该 this 将引用该函数所调用的对象。
When this keyword is used inside a function, the this will refer to the object that the function is called with.
在 JavaScript 中,函数也是对象。因此,你还可以将“this”关键字与函数一起使用。
In JavaScript, functions are also objects. So, you can use the 'this' keyword with functions also.
Which object does the 'this' refer to?
由“ this ”关键字引用的对象取决于你如何使用“this”关键字。
The object referred by the 'this' keyword depends on how you have used the 'this' keyword.
例如,
For example,
-
The 'this' keyword refers to the window object in the global scope.
-
When you use the 'this' keyword inside the function, it also represents the 'window' object.
-
The 'this' keyword refers to an undefined in the strict mode in the function.
-
The 'this' keyword refers to the object when you use it in the object method.
-
In the event handler, the 'this' keyword refers to the element on which the event is executed.
-
The 'this' keyword in methods like call(), apply(), and bind() can refer to different objects.
Syntax
按照下面语法在 JavaScript 中使用“this”关键字−
Follow the syntax below to use the 'this' keyword in JavaScript &minus
this.property
OR
this.method();
您可以使用“this”关键字访问属性并执行对象的方法。
You can access the properties and execute the object’s methods using the 'this' keyword.
JavaScript 'this' in the Global Scope
在全局作用域中使用“this”关键字时,它表示全局(窗口)对象。在全局作用域中,您可以使用“this”关键字访问全局变量。
When you use the 'this' keyword in the global scope, it represents the global (window) object. You can access the global variables using the 'this' keyword in the global scope.
Example
在下面的代码中,我们在全局作用域中定义了“num”变量和 printNum() 函数。之后,我们使用“this”关键字访问全局变量和函数。
In the below code, we have defined the 'num' variable and printNum() function in the global scope. After that, we used the 'this' keyword to access the global variable and functions.
<html>
<body>
<div id = "demo"> </div>
<script>
const output = document.getElementById('demo');
var num = 10;
function printNum() {
output.innerHTML += "Inside the function: " + num + "<br>";
}
this.printNum();
output.innerHTML += "Outside the function: " + this.num + "<br>";
</script>
</body>
</html>
Inside the function: 10
Outside the function: 10
JavaScript 'this' in a Function
在函数中使用“this”关键字时,它表示全局作用域或“窗口”对象。
When you use the 'this' keyword in the function, it represents the global scope or 'window' object.
Example
在下面的代码中,我们在函数内部使用了“this”关键字。您会看到,我们使用“this”关键字访问函数内部的全局变量。
In the below code, we use the 'this' keyword inside the function. You can observe that we access the global variables using the 'this' keyword inside the function.
<html>
<body>
<div id = "demo"> </div>
<script>
const output = document.getElementById('demo');
var message = "Hello World!";
function printMessage() {
var message = "Hi! How are you?";
output.innerHTML = "The messsage is: " + this.message;
}
printMessage();
</script>
</body>
</html>
The messsage is: Hello World!
'this' in a Function in Strict Mode
在严格模式中函数内部使用“this”关键字时,它不会引用任何对象。“this”关键字的值变为未定义。
When you use the 'this' keyword inside the function in the strict mode, it doesn’t refer to any object. The value of the 'this' keyword becomes undefined.
Example
在下面的代码中,我们在严格模式中函数内部使用了“this”关键字。它输出 undefined。
In the below code, we use the 'this' keyword inside the function in the strict mode. It prints undefined.
<html>
<body>
<div id = "demo"> </div>
<script>
let output = document.getElementById('demo');
var message = "Hello World!";
function test() {
"use strict";
output.innerHTML = "The value of this in the strict mode is: " + this;
}
test();
</script>
</body>
</html>
The value of this in the strict mode is: undefined
'this' in a Constructor Function
当您使用函数作为构造函数创建对象时,“this”关键字表示该对象。
When you use the function as a constructor function to create an object, the 'this' keyword refers to the object.
Example
我们在下面的代码中定义了 Animal() 构造函数。我们在构造函数内部使用了“this”关键字初始化对象的属性。
We have defined the Animal() constructor function in the code below. We used the 'this' keyword inside the constructor function to initialize the properties of the object.
<html>
<body>
<div id = "demo"> </div>
<script>
const output = document.getElementById('demo');
function Animal() {
this.name = 'Lion';
this.age = 3;
this.color = 'Brown';
}
const newAnimal = new Animal();
output.innerHTML = "Animal Name: " + newAnimal.name + "<br>";
output.innerHTML += "Animal Age: " + newAnimal.age + "<br>";
output.innerHTML += "Animal Color: " + newAnimal.color;
</script>
</body>
</html>
Animal Name: Lion
Animal Age: 3
Animal Color: Brown
'this' in an Arrow Function
在箭头函数中使用“this”关键字时,它表示其父对象的范围。
When you use the 'this' keyword in the arrow function, it refers to the scope of its parent object.
例如,当您在对象方法中定义箭头函数并在其中使用“this”关键字时,它表示对象。如果您在另一个函数中定义箭头函数,“this”关键字表示全局对象。
For example, when you define the arrow function inside the object method and use the 'this' keyword inside that, it presents the object. The 'this' keyword refers to the global object if you define the arrow function inside another function.
Example
在下面的代码中,我们在对象的 getDetails() 方法中定义了箭头函数。当我们打印“this”关键字的值时,它会打印对象。
In the below code, we have defined the arrow function inside the getDetails() method of the object. When we print the value of the 'this' keyword, it prints the object.
<html>
<body>
<div id = "output1">Value of 'this' inside the getDetails() method: </div>
<div id = "output2">Value of 'this' inside the getInnerDetails() method: </div>
<script>
const wall = {
size: "10",
color: "blue",
getDetails() {
document.getElementById('output1').innerHTML += JSON.stringify(this);
const getInnerDetails = () => {
document.getElementById('output2').innerHTML += JSON.stringify(this);
}
getInnerDetails();
}
}
wall.getDetails();
</script>
</body>
</html>
Value of 'this' inside the getDetails() method: {"size":"10","color":"blue"}
Value of 'this' inside the getInnerDetails() method: {"size":"10","color":"blue"}
'this' in the Object Method
在对象方法中使用“this”关键字时,它表示对象本身。
When you use the 'this' keyword inside the object method, it represents the object itself.
Example
在下面的代码中,我们定义了“fruit”对象。该对象包含 printFruitDetails() 方法,在该方法中我们使用“this”关键字访问对象的属性。
In the below code, we have defined the 'fruit; object. The object contains the printFruitDetails() method, and in the method, we used the 'this' keyword to access the properties of the object.
<html>
<body>
<div id = "demo"> </div>
<script>
const output = document.getElementById('demo');
const fruit = {
name: "Apple",
color: "red",
printFruitDetails() {
output.innerHTML += "Furit Name = " + this.name + "<br>";
output.innerHTML += "Fruit Color = " + this.color;
}
}
fruit.printFruitDetails();
</script>
</body>
</html>
Furit Name = Apple
Fruit Color = red
'this' in a Child Function of an Object Method
当您在对象方法中定义函数并在函数中使用“this”关键字时,它表示全局对象,而不是对象。
When you define the function inside the object method and use the 'this' keyword inside the function, it represents the global object rather than an object.
Example:
在下面的代码中,我们定义了 person 对象。person 对象包含 printDetails() 方法。在 printDetails() 方法中,我们定义了 printThis() 函数。
In the below code, we have defined the person object. The person object contains the printDetails() method. In the printDetails() method, we have defined the printThis() function.
在 printThis() 函数中,我们打印“this”关键字的值,它会打印全局对象。
In the printThis() function, we print the value of the 'this' keyword, and it prints the global object.
<html>
<body>
<div id = "output">Inside the printThis() function, Value of 'this' = </div>
<script>
const person = {
name: "Salman",
isBusinessman: false,
printDetails() {
function printThis() {
document.getElementById('output').innerHTML += this;
}
printThis();
}
}
person.printDetails();
</script>
</body>
</html>
Inside the printThis() function, Value of 'this' = [object Window]
JavaScript 'this' in Event Handlers
在事件处理程序中使用“this”关键字是指执行该事件的 HTML 元素。
Using the 'this' keyword with event handlers refers to the HTML element on which the event is executed.
Example
在下面的代码中,我们在 <div> 元素中添加了 onClick 事件处理程序。当用户单击 div 元素时,我们使用' display' 属性隐藏 div 元素。
In the below code, we have added the onClick event handler into the <div> element. When users click the div element, we hide the div element using the 'display' property.
<html>
<head>
<style>
div {
height: 200px;
width: 700px;
background-color: red;
}
</style>
</head>
<body>
<p>Click the DIV below to remove it. </p>
<div onclick = "this.style.display = 'none'"> </div>
</body>
</html>
Explicit Function Binding in JavaScript
在 JavaScript 中,call()、apply() 或 bind() 方法用于显式绑定。
In JavaScript, call(), apply(), or bind() methods are used for the explicit binding.
显式绑定允许您借用特定对象的 method。使用这些方法,您可以明确定义“this”关键字的上下文。
The explicit binding allows you to borrow the method of the particular object. Using these methods, you can explicitly define the context of the 'this' keyword.
下面我们通过示例了解显式绑定。
Let’s understand explicit binding using the examples below.
Example: Using the call() method
在下面的代码中,lion 对象包含颜色和年龄属性。它还包含 printDetails() 方法并使用“this”关键字打印详细信息。
In the below code, the lion object contains the color and age property. It also contains the printDetails() method and prints the details using the 'this' keyword.
tiger 对象仅包含颜色和年龄属性。我们使用 call() 方法在 tiger 对象的上下文中调用 lion 对象的 printDetails() 方法。因此,该方法在输出中打印了 tiger 的详细信息。
The tiger object contains only color and age properties. We used the call() method to call the printDetails() method of the lion object with the context of the tiger object. So, the method prints the details of the tiger in the output.
<html>
<body>
<div id = "demo"> </div>
<script>
const output = document.getElementById('demo');
const lion = {
color: "Yellow",
age: 10,
printDetails() {
output.innerHTML += `<p>Color: ${this.color}</p>`;
output.innerHTML += `<p>Age: ${this.age}</p>`;
}
}
const tiger = {
color: "Orange",
age: 15,
}
lion.printDetails.call(tiger);
</script>
</body>
</html>
Color: Orange
Age: 15
Example: Using the bind() method
下面的代码也包含 lion 和 tiger 对象。然后,我们使用 bind() 方法将 lion 对象的 printDetails() 方法绑定到 tiger 对象中。
The below code also contains the lion and tiger objects. After that, we used the bind() method to bind the printDetails() method of the lion object into the tiger object.
然后,我们使用 tigerDetails() 方法打印 tiger 对象的详细信息。
After that, we use the tigerDetails() method to print the details of the tiger object.
<html>
<body>
<div id = "demo"> </div>
<script>
const output = document.getElementById('demo');
const lion = {
color: "Yellow",
age: 10,
printDetails() {
output.innerHTML += `<p>Color: ${this.color}</p>`;
output.innerHTML += `<p>Age: ${this.age}</p>`;
}
}
const tiger = {
color: "Orange",
age: 15,
}
const tigerDetails = lion.printDetails.bind(tiger);
tigerDetails();
</script>
</body>
</html>
Color: Orange
Age: 15