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:
var obj = {
key1: "it ",
key2: key1 " works!"
};
alert(obj.key2);
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:
var obj = {
key1: "it ",
key2: function() {
return this.key1 " works!";
}
};
alert(obj.key2());
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!".
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3