1

If I create an instance of a reference type in a memory-managed language like JavaScript:

var foo = {};

I presume something like the following is added to the stack:

 foo | <memory address of the actual instance on the heap>

So foo is a reference to an area of memory elsewhere.

With pointers in a language like C, you have to explicitly dereference the pointer to get hold of the memory on the heap it points at.

So is it correct to say that the variable foo is "automatically dereferenced" in a language like JavaScript? Or is that just an implied behavior when the term reference is used instead of pointer?

/**
* `foo` is dereferenced to the memory 
* corresponding to the instance on the 
* heap. The interpreter expects to find 
* an object at that location, parses the 
* memory as such, finds the method `bar` 
* and invokes it.
*/
foo.bar();
Ben Aston
  • 53,718
  • 65
  • 205
  • 331
  • JS does not allow access to the memory directly, it would be a security flaw, thus there aren't really any APIs for pointers. – vol7ron Jan 24 '15 at 16:30
  • To answer your other question, yes. When you pass an object as an argument you are passing its reference, not its value. This is why modifying a property of an object from within a function also alters the source object outside the function. However the dereferencing is done automatically, the object is treated like any other variable. – vol7ron Jan 24 '15 at 16:39
  • Exactly what is going on behind the scenes is not defined by JavaScript. It could create an object, foo, and create an object ,{}, and give the first a pointer to the second. It could assign foo to foo2, so they both have pointers to {}, then assign something else to foo, and so on. Or the interpreter/compiler may find a better way of doing things. – QuentinUK Jan 24 '15 at 16:40
  • It's not defined and its dependent on which JS engine is being used. Interpreters have their own way of dealing with it and IIRC none of them expose addresses, which would be useful at times for debugging. I think that has more to do with speed. – vol7ron Jan 24 '15 at 16:44
  • 1
    You might be interested in the lower part of [this answer](http://stackoverflow.com/a/23556036/1048572) – Bergi Mar 03 '15 at 19:44

0 Answers0