How to Reference Internal Values within a JavaScript Object
In JavaScript, accessing values within an object that refer to other values within the same object can sometimes be challenging. Consider the following code snippet:
<code class="js">var obj = { key1: "it ", key2: key1 + " works!" }; alert(obj.key2);</code>
This code errors with the message "key1 is not defined." To resolve this issue, you can use the special keyword this. However, attempts to access this.key1 or this[key1] within the object will still result in errors.
Using a Function to Reference Internal Values
Instead of using direct property access, you can define a function within the object that returns the desired value. For example:
<code class="js">var obj = { key1: "it ", key2: function() { return this.key1 + " works!"; } }; alert(obj.key2());</code>
By defining key2 as a function, we gain access to the this keyword within the object, allowing us to reference key1. The alert() function will now display the correct output, "it works!".
The above is the detailed content of How Can I Reference Internal Values within a JavaScript Object?. For more information, please follow other related articles on the PHP Chinese website!