Object methods, this

JavaScript Object Methods, “this” (JavaScript对象方法, “this”)

In JavaScript, objects are created for representing real-world entities, such as orders, users, and more. Here is an example:

let site = {
 name: "w3cdoc",
};
console.log(site);

In the real world, you act like this: login, logout, choose something from a shopping cart, and more.

In JavaScript, you can represent actions by functions in properties. (在JavaScript中,您可以在属性中按函数表示操作。)

Examples of Methods

Examples of Methods (方法示例)

Your first step while studying JavaScript object methods should be to learn how to “say welcome”. The example will look like this:

let site = {
 name: "w3cdoc",
};
site.welcome = function () {
 console.log("Welcome to w3cdoc!");
};
site.welcome(); // Welcome to w3cdoc!

Function Expression (函数表达式)

site.welcome

So, site can respond only after calling it. (因此,站点只有在调用后才能响应。)

A particular function that is the property of an object is known as a method. (作为对象属性的特定函数称为方法。) In the example given above, welcome is a method of the object site. (在上面的示例中, welcome是对象站点的一种方法。)

Moreover, a pre-declared function can be used as a method. To do that, you need to invoke the following command:

let site = {
 name: "w3cdoc",
};
site.welcome = function () {
 console.log("Welcome to w3cdoc!");
};
site.welcome(); // Welcome to w3cdoc!

Description of Object-oriented Programming

Description of Object-oriented Programming (面向对象编程的描述)

Object-oriented programming (in short “OOP”) is targeted at writing codes by using objects to represent entities. (面向对象编程(简称“OOP” )的目标是通过使用对象来表示实体来编写代码。)

OOP can be described as a science of its own. A lot of research has been done to fully explore how to choose the right entities, how to organize the interconnection between them, and a lot more. That’s a whole new architecture. (OOP可以被描述为一门科学。已经做了大量的研究来充分探索如何选择合适的实体,如何组织它们之间的互连,以及更多。这是一个全新的架构。)

Shorthand of Method

Shorthand of Method (方法的速记)

You can use a short syntax for methods in an object like this:

// method shorthand
let site = {
 welcome() { 
   console.log("Welcome to w3cdoc");
 }
};
site.welcome();

In this example, you can see that the word “function” is omitted, and it’s just written welcome. Of course, there can be differences linked with object inheritance. Anyway, in most of the cases, it is more preferred to use a shorter syntax. (在此示例中,您可以看到“function”一词被省略,只是写成welcome。当然,也可能存在与对象继承相关的差异。无论如何,在大多数情况下,更倾向于使用较短的语法。)

“this” in Object Methods

“this” in Object Methods (对象方法中的“this”)

Generally, for doing its job, an object method must have the information kept in the object. (一般来说,为了完成其工作,对象方法必须将信息保存在对象中。)

For example, the code that is inside site.welcome() might need the site.name. (例如, site.welcome ()中的代码可能需要site.name。)

A method can use “this” keyword for accessing the object. (方法可以使用“this”关键字来访问对象。)

The object “before dot” should be the value of “this”. (对象“before dot”应为“this”的值。)

For instance, you can call the method as follows:

let site = {
 name: "w3cdoc",
 welcome() {
   // "this" is the "current object"
(//“this”是“current object”)
   console.log(this.name);
 }
};
site.welcome(); // w3cdoc

In the above-given example, while executing site.welcome(), site will be the value of “this”. (在上述示例中,在执行site.welcome ()时, site将是“this”的值。)

You have the option of accessing the object without using “this”. Just reference it via the outer variable like this:

let site = {
 name: "w3cdoc",
 welcome() {
   console.log(site.name); // "site" instead of "this"
 }
};
site.welcome();

But, take into consideration that such kinds of codes can’t be reliable. In case of copying the site to a different variable (for example, anotherSite = site) overwriting site with another thing, you will be directed to a wrong object. (但是,请考虑此类代码不可靠。如果将网站复制到其他变量(例如, anotherSite = site ) ,用其他东西覆盖网站,您将被定向到错误的对象。)

Here is an example:

let site = {
 name: "w3cdoc",
 welcome() {
   console.log(site.name); // leads to an error
 }
};
let anotherSite = site;
site = null; // overwrite to make things obvious
anotherSite.welcome(); // Whoops! inside welcome(), the old name is used! error!

“this” can be Unbound

“this” can be Unbound (“this”可以解除绑定)

Commonly, the JavaScript keyword “this” can be used in any function on the contrary with other programming languages. (通常,与其他编程语言相反, JavaScript关键字“this”可用于任何函数。)

The following example doesn’t have any syntax errors:

function welcome() {
 console.log(this.name);
}

In the following example, the same function is accredited to 2 different objects, and it includes different distinctive “this” in the invocations:

let site = {
 name: "w3cdoc"
};
let anotherSite = {
 name: "anotherSite"
};
function welcome() {
 console.log(this.name);
}
// use the same function in two objects
site.func = welcome;
anotherSite.func = welcome;
// these calls have different this
// "this" inside the function is the object "before the dot"
site.func(); // w3cdoc (this == site)
anotherSite.func(); // anotherSite  (this == anotherSite)
anotherSite['func'](); // anotherSite (dot or square brackets access the method – doesn't matter)

So, simple steps are used here: If you first call obj.func(), then you need to run this is obj during the invocation of func. This means that in the above-given example, either site or anotherSite is used.

Invoking without an object: this == undefined

The function can even be called without an object as follows:

function welcome() {
 console.log(this);
}
welcome();

In the above-mentioned example, this is undefined in the strict mode. In the event of trying to enter this.name, an error can occur. (在上述示例中,在严格模式下这是未定义的。如果尝试输入this.name ,可能会发生错误。)

The value of “this” in a non-strict mode will be the global object. (在非严格模式下, “this”的值将是全局对象。)

Commonly, a call like this can cause a programming error. In case there is this in the function, it should be invoked in the object context. (通常,这样的调用可能会导致编程错误。如果函数中存在此属性,则应在对象上下文中调用它。)

Outcomes of Unbound “this”

Outcomes of Unbound “this” (未绑定“this”的结果)

If you are already used to another programming language, possibly you are familiar with the idea of “bound this” in which methods, characterized in an object always obtain “this” referencing the object. (如果您已经习惯了另一种编程语言,那么您可能熟悉“绑定this”的想法,其中以对象为特征的方法总是获得引用该对象的“this”。)

“this” can be described as free in JavaScript. Hence its value doesn’t depend on where the method was confirmed. But it more depends on the “before dot” object. (“this”可以在JavaScript中描述为免费。因此,其值不取决于方法的确认位置。但它更多地取决于“before dot”对象。)

The given concept of “this” has both advantages and disadvantages. On the one hand, you can use the function for a variety of objects. On the other side, the more flexibility, the more chances to make mistakes. Your aim should be to learn how to work with it to get benefits and avoid mistakes. (给定的“this”概念既有优点也有缺点。一方面,您可以将函数用于各种对象。另一方面,灵活性越高,犯错的可能性就越大。你的目标应该是学习如何使用它来获得好处并避免错误。)

Arrow Functions Don’t Have “this”

Arrow Functions Don’t Have “this” (箭头函数没有“this”)

Arrow functions are unique as they don’t have their own “this”. In case you start referencing it from a function like that, it will be taken from an outer “normal” function. (箭头函数是唯一的,因为它们没有自己的“this”。如果您从这样的函数开始引用它,它将从外部“正常”函数中获取。)

In the following example, arrow() uses this from the method: site.welcome().

let site = {
 name: "w3cdoc",
 welcome() {
   let arrow = () => console.log(this.name);
   arrow();
 }
};
site.welcome(); // w3cdoc

The special arrow function method is especially useful when you don’t wish to have a separate “this” but want to take it from a context beyond. (当您不希望有一个单独的“this” ,而是希望从其他上下文中获取它时,特殊箭头函数方法特别有用。)



请遵守《互联网环境法规》文明发言,欢迎讨论问题
扫码反馈

扫一扫,反馈当前页面

咨询反馈
扫码关注
返回顶部