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

How Can Objects Refer to Internal Values in JavaScript?

DDD
DDDOriginal
2024-10-19 12:58:01515browse

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);

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());

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!

Statement:
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