In JavaScript primitive types, such as integers and strings, are passed by value, whereas objects are passed by reference. In order to achieve your desired functionality, you need to use property of an object:
var humanWidth = {value: 0};
var maleWidth = humanWidth;
humanWidth.value = 170;
alert(maleWidth.value); // Returns 170!
Update: If you want to use anonymous function with an expression, not just an "alias" for the same value, try this:
var humanWidth = {value: 0};
var maleWidth = new function() {
Object.defineProperty(this, "value", {
get: function() {
return humanWidth.value * 2;
}
});
};
humanWidth.value = 170;
alert(maleWidth.value); // Returns 340!
Update 2: Probably more elegant and less confusing solution (wihout new function()
):
var data = {humanWidth: 0};
Object.defineProperty(data, "maleWidth", {
get: function() {
return this.humanWidth * 2;
}
}
);
data.humanWidth = 170;
alert(data.maleWidth); // Returns 340!
Note that this time, unlike the previous two, both humanWidth
and maleWidth
are properties of one object (called data
).