1

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);

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

That works. Unfortunately, slide is just a primitive, so T.J. Crowder said I already have it right. I can't make this code any shorter.
Yes, that's true - I just mean what I wrote as an illustrative example.
2

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.

1 Comment

Thanks for the confirmation. Just wanted to make sure I did not misunderstanding this aspect of Javascript.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.