开发者

Question about Javascript pointer to an object property

开发者 https://www.devze.com 2023-02-26 05:27 出处:网络
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

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;开发者_JAVA百科
    };
}());

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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消