Stephen
Stephen

Reputation: 2550

Question about Javascript pointer to an object property

I wanted to set a variable to point to property in an newly created object to save a "lookup" as shown in the example below. Basically, I thought the variable is a reference to the object's property. This is not the case; it looks like the variable holds the value. The first console.log is 1 (which is the value I want to assign to photoGalleryMod.slide) but when looking at photoGalleryMod.slide, it's still 0.

Is there a way to do this? Thanks.

(function() {
    var instance;

    PhotoGalleryModule = function PhotoGalleryModule() {

        if (instance) {
            return instance;
        }

        instance = this;

        /* Properties */
        this.slide = 0;
    };
}());

window.photoGalleryMod = new PhotoGalleryModule();

/* Tried to set a variable so I could use test, instead of writing photoGalleryMod.slide all the time plus it saves a lookup */

var test = photoGalleryMod.slide;

test = test + 1;

console.log(test);
console.log(photoGalleryMod.slide);

Upvotes: 1

Views: 4406

Answers (2)

Pointy
Pointy

Reputation: 413709

Yes, you're making a copy of the value, because "slide" is set to a primitive type. Try this:

this.slide = [0];

and then

var test = photoGalleryMod.slide;
test[0] = test[0] + 1;

then change the logging:

console.log(test[0]);
console.log(photoGalleryMod.slide[0]);

In that case you'll see that you do have a reference to the same object. Unlike some other languages (C++) there's no way to say, "Please give me an alias for this variable" in JavaScript.

Upvotes: 3

T.J. Crowder
T.J. Crowder

Reputation: 1074276

it looks like the variable holds the value

That's correct. Since you're using number primitives, variables contain the value rather than pointing to it. Variables only contain references when they're referring to objects.

The way to do it is to use an object property and to point to the object — which is exactly what you have with photoGalleryMod and its slide property.

Upvotes: 2

Related Questions