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!