Home > Web Front-end > JS Tutorial > How Can Objects Refer to Internal Values in JavaScript?

How Can Objects Refer to Internal Values in JavaScript?

DDD
Release: 2024-10-19 12:58:01
Original
596 people have browsed it

How Can Objects Refer to Internal Values in JavaScript?

How can a JavaScript object refer to values within itself?

Consider the following JavaScript code snippet:

var obj = {
 key1 : "it ",
 key2 : key1 + " works!"
};
alert(obj.key2);
Copy after login

This code raises an error because "key1" is undefined within the scope of "key2." Various attempts to access "key1" using "this," brackets, and quotes have proven unsuccessful.

How to Refer to Values within an Object

To resolve this issue and allow "key2" to reference "key1's" value, consider using a function within the object definition, as shown below:

var obj = {
  key1: "it ",
  key2: function() {
    return this.key1 + " works!";
  }
};

alert(obj.key2());
Copy after login

In this instance, the function within "key2" has access to the object's internal state, including the "key1" property. When the "key2" function is invoked, it retrieves "key1's" value and concatenates it with the specified string. The resulting value is then returned and displayed as an alert.

The above is the detailed content of How Can Objects Refer to Internal Values in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php
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