了解云计算_了解

了解云计算

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()的全局范围版本时,我们使用全局范围的变量SnagDachshund因为函数中的this关键字引用了全局对象。 当我们调用dog对象的getDog()方法时,它指的是dog对象的特性SnufflesFrench 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 be undefined

    在函数中,在严格模式下, thisundefined

  • In an arrow function, this retains the value of the enclosing lexical context’s this

    在箭头函数中, 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

了解云计算

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值