关于指向对象属性的 Javascript 指针的问题 [英] Question about Javascript pointer to an object property

查看:61
本文介绍了关于指向对象属性的 Javascript 指针的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设置一个变量以指向新创建的对象中的属性,以保存查找",如下例所示.基本上,我认为变量是对对象属性的引用.不是这种情况;看起来变量保存了值.第一个 console.log 是 1(这是我想分配给 photoGalleryMod.slide 的值)但是在查看 photoGalleryMod.slide 时,它​​仍然是 0.

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

推荐答案

看起来变量保存了值

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.

这样做的方法是使用对象属性并指向该对象 —这正是您使用 photoGalleryMod 及其 slide 属性所拥有的.

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.

这篇关于关于指向对象属性的 Javascript 指针的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆