Question

After answering this question about using the style.top property of a div in jQuery's $.animate(), I started to wonder if there was a way to do it more in line with what the OP had thought (s)he could do.

The question is: can we get a direct reference to an object's property when that property is a primitive type?

For example, if you had an object called myDiv, you could get a reference to its style property, because that's an object, but is there any way to get a reference to the top property of style so that when this changes, you don't have to retrieve it again and again? (Note: I'm not saying this retrieval is computationally significant. This is just a question about what's possible, not what's good practice.)

var myDiv = document.getElementById('myDiv');

myDiv.style.top = "100px";
var myDivStyle = myDiv.style;
var myDivStyleTop = myDiv.style.top;

myDiv.style.top = "200px";
console.log(myDivStyle.top); // will print "200px"
console.log(myDivStyleTop); // will obviously print "100px"

Is there a way to reference that top property directly without going through style? My instinct is no, but JS has surprised me before, so I just wanted to make sure.

Was it helpful?

Solution

No. A variable are just simple container that can hold a value. Assigning a new value to a variable can never change the value of another variable or property.

In this regard, it doesn't matter whether the variable holds a primitive values or an object, that's just how variables work.

OTHER TIPS

No there isn't. Primitives are immutable and never stored by reference.

From MDN

object reference

A link to an object. Object references can be used as if they were the objects they link to. The concept of object references arises when assigning the same object to more than one property. Each assigned property does not hold a copy of the object. Instead, they hold object references that link to the same object. In practice, this means that if the object is modified, all properties referring to the object reflect the modification.

primitive, primitive value

A data that is not an object and does not have any methods. JavaScript has 5 primitive datatypes: string, number, boolean, null, undefined. With the exception of null and undefined, all primitives values have object equivalents which wrap around the primitive values, e.g. a String object wraps around a string primitive. All primitives are immutable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top