Home > Web Front-end > JS Tutorial > How Does the `this` Keyword Behave Inside a JavaScript Object Literal?

How Does the `this` Keyword Behave Inside a JavaScript Object Literal?

DDD
Release: 2024-12-26 03:24:08
Original
639 people have browsed it

How Does the `this` Keyword Behave Inside a JavaScript Object Literal?

How the "this" Keyword Behaves Within an Object Literal in JavaScript

In JavaScript, the "this" keyword refers to the current object upon which the function was invoked. However, the binding of "this" can be confusing, especially when used within object literals.

Within an object literal, the value of "this" is not bound to the object itself but rather to the global object (window in browsers). This can lead to unexpected behavior, as seen in the following code:

var obj1 = {
  foo: new Date(),
  bar: new MyDate(this.foo)  //  this.foo is undefined
};
Copy after login

In this example, "this.foo" is undefined within the constructor of MyDate because "this" refers to the global object, which doesn't have a property named "foo."

To resolve this issue, you can explicitly bind "this" within the object literal using the bind() method:

var obj4 = {};
obj4.foo = new Date();
obj4.bar = new MyDate(obj4.foo.bind(obj4));
Copy after login

This ensures that "this" inside the constructor of MyDate refers to the correct object (obj4).

Alternatively, you can use an arrow function to bind "this" to the object:

var obj3 = {
  foo: new Date(),
  bar: new MyDate(() => this.foo)
};
Copy after login

In arrow functions, "this" is bound to the surrounding scope at the time of definition, which in this case is the object itself.

The above is the detailed content of How Does the `this` Keyword Behave Inside a JavaScript Object Literal?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template