Reputation: 13
I am reading a book Wrox Professinal Javascript for web developer. In a chapter Author is explaining about different variable types - primitive and reference. For reference type variable, this is written in the book - "Reference values are objects stored in memory. Unlike other languages, JavaScript does not permit direct access of memory locations, so direct manipulation of the object’s memory space is not allowed. When you manipulate an object, you’re really working on a reference to that object rather than the actual object itself. For this reason, such values are said to be accessed by reference." Can anyone explain what it means.
Upvotes: 1
Views: 61
Reputation: 24955
Reference values are objects stored in memory.
This specifies that Objects in Javascript are linked with reference. What this means is, when you do var obj = {};
, an object is created in memory and is stored in say location x100006
. So obj
will hold this x100006
value and not {}
.
Unlike other languages, JavaScript does not permit direct access of memory locations, so direct manipulation of the object’s memory space is not allowed.
What this says is, since I know the memory location of obj
from above example, I cannot set a variable to manually point to this location. In reality, you will not know the location. You just know that there is a pointer reference and assignment operation copies that value. So when you do var newObj = obj
, you copy reference and not object value. Still you do not know the memory location that you can play, like in C and C++.
When you manipulate an object, you’re really working on a reference to that object rather than the actual object itself. For this reason, such values are said to be accessed by reference
Now that we know obj
and newObj
have reference to the object and not actual object, if you manipulate the value, you are making changes to the object at this memory location. So if I do obj.x = 'foo'
, this will reflect in newObj
as well.
Upvotes: 0
Reputation: 1658
Whether you can alias something depends on the data type. Objects, arrays, and functions will be handled by reference and aliasing is possible. Other types are essentially atomic, and the variable stores the value rather than a reference to a value.
Upvotes: 1