了解云计算
The this
keyword in JavaScript is a core concept of the language and can cause confusion for beginners and more advanced developers alike. In this article, I am going to explain the this
keyword, and its value in different use cases.
JavaScript中的this
关键字是该语言的核心概念,可能会给初学者和更高级的开发人员造成混乱。 在本文中,我将解释this
关键字及其在不同用例中的价值。
What is this?
这是什么?
Every time we run some JavaScript in a web browser, the engine executes multiple steps, one of them being the creation of an execution context. Execution context is an abstract concept, but it refers to the environment in which the code is evaluated and then executed.
每当我们在网络浏览器中运行一些JavaScript时,引擎就会执行多个步骤,其中之一就是创建执行上下文 。 执行上下文是一个抽象概念,但它指的是在其中评估代码然后执行代码的环境。
Every execution context references an object and that object references the this
keyword. The this
keyword is a reference to the object which called the function. The value of this
, therefore, depends on where it has been used.
每个执行上下文都引用一个对象,并且该对象引用this
关键字。 this
关键字是对称为函数的对象的引用。 因此, this
的值取决于它的使用位置。
Global context
全球背景
In the global execution context, this
refers to the global object, which in the case of the browser is called window
.
在全球执行上下文, this
指的是全局对象 ,这在浏览器的情况下被称为window
。
console.log(this === window); // truevar colour = 'red';function getColour() {
var colour = 'purple';
console.log('colour', colour); // colour purple
console.log('this.colour', this.colour); // this.colour red
}getColour();
The getColour()
function is called in the global scope, and the first colour
variable is included in the global scope as well. If we console.log(this)
, the window method has a getColour()
method and a colour
property. When we call this.colour
at this point, it will return red
, but the local variable colour will return purple
.
getColour()
函数在全局范围内调用,并且第一个colour
变量也包含在全局范围内。 如果我们console.log(this)
,则window方法具有getColour()
方法和colour
属性。 当我们在此时调用this.colour
时,它将返回red
,但是局部变量color将返回purple
。
In this example, this
refers to the window
object so this.colour
refers to the global colour
property.
在此示例中, this
引用window
对象,因此this.colour
引用全局colour
属性。
It’s worth noting that if JavaScript has strict mode enabled then this
in global scope is undefined
.
值得一提的是,如果JavaScript有启用严格模式,那么this
在全球范围undefined
。
Object methods
对象方法
In the instance of creating a new object using a constructor, the this
keyword refers to the new instance of the object.
在使用构造函数创建新对象的实例中, this
关键字引用对象的新实例。
var firstName = 'Brad';
var lastName = 'Pitt';function User(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.returnName = function() {
return `${this.firstName} ${this.lastName}`;
};
}let newUser = new User('George', 'Clooney');console.log(newUser.returnName()); // George Clooney
When calling the returnUser()
method, this
will reference the newUser
object which was created using the User
constructor. The value will be George Clooney
, not Brad Pitt
, as we are using newUser
object properties.
当调用returnUser()
方法, this
将参考newUser
其使用所创建的对象User
的构造函数。 该值将是George Clooney
,而不是Brad Pitt
,因为我们正在使用newUser
对象属性。
Inside functions
内部功能
The use of this
inside function calls can be confusing. A function in JavaScript is an object, it has its own properties and one of them is this
. Its value depends on how it’s invoked.
使用this
内部函数调用可能会造成混淆。 JavaScript中的函数是一个对象,它具有自己的属性,其中之一就是this
。 它的值取决于它的调用方式。
var dogName = 'Snag';
var dogBreed = 'Dachshund';function getDog() {
return `${this.dogName} the ${this.dogBreed}`;
}var dog = {
dogName: 'Snuffles',
dogBreed: 'French Bulldog',
getDog: function() {
return `${this.dogName} the ${this.dogBreed}`;
}
}console.log('Dog in global scope:', getDog()); // Dog in global scope: Snag the Dachshundconsole.log('Dog in object scope:', dog.getDog()); // Dog in object scope: Snuffles the French Bulldog
In this code there are two functions, one is in the global scope and the other is a dog
object method. When we call the global scope version of getDog()
we use the globally scoped variables Snag
and Dachshund
because the this
keyword in the function refers to the global object. When we call the getDog()
method of the dog
object this refers to the dog
object properties Snuffles
and French Bulldog
.
在此代码中,有两个函数,一个在全局范围内,另一个是dog
对象方法。 当我们调用getDog()
的全局范围版本时,我们使用全局范围的变量Snag
和Dachshund
因为函数中的this
关键字引用了全局对象。 当我们调用dog
对象的getDog()
方法时,它指的是dog
对象的特性Snuffles
和French Bulldog
。
This demonstrates how we can get two different results using this
in similar functions.
这说明了如何在类似的函数中使用this
来获得两个不同的结果。
Arrow functions
箭头功能
Arrow functions are an exception to the above rules. They don’t have their own this
. If we reference this
inside of an arrow function it refers to the this
from the outer context.
箭头功能是上述规则的例外。 他们没有自己的this
。 如果我们引用this
箭头函数的里面是指在this
从外部上下文。
let user = {
name: 'Mario',
sayHi() {
name: 'Luigi';
let myFunction = () => console.log(`Hi ${this.name}!`);
myFunction();
}
};user.sayHi(); // Hi Mario!
With events
有事件
With events, after we trigger an event we call the event handler. When we use the this
keyword in an event handler it refers to the HTML element which triggered the function.
对于事件,触发事件后,我们将调用事件处理程序。 当我们在事件处理程序中使用this
关键字时,它表示触发函数HTML元素。
<button class="button myButton">Click</button>const button = document.querySelector('.myButton');button.addEventListener('click', function() {
console.log(this === button); // true
});
Summary
摘要
By default,
this
refers to the global object默认情况下,
this
是指全局对象In an object method,
this
refers to the object the method was called on在对象方法中,
this
是指调用该方法的对象In a function, when JavaScript is not in strict mode,
this
refers to the global object在函数中,当JavaScript不在严格模式下时,
this
是指全局对象In a function, when in strict mode,
this
will beundefined
在函数中,在严格模式下,
this
是undefined
In an arrow function,
this
retains the value of the enclosing lexical context’sthis
在箭头函数中,
this
保留了封闭词法上下文this
的值。In a constructor call,
this
is bound to the new object that gets constructed在构造函数调用中,
this
绑定到要构造的新对象In an event handler,
this
is bound to the HTML element on which the listener is placed在事件处理程序中,
this
绑定到侦听器所在HTML元素
翻译自: https://medium.com/@gemma.stiles/understanding-the-this-keyword-in-javascript-1f6882592a84
了解云计算