关于Javascript指向对象属性的指针的问题
我想设置一个变量来指向新创建的对象中的属性以保存“查找”,如下例所示。基本上,我认为变量是对对象属性的引用。事实并非如此;看起来变量保存了值。第一个console.log是1(这是我想分配给photoGalleryMod.slide的值),但是当查看photoGalleryMod.slide时,它仍然是0。
有没有办法做到这一点?谢谢。
(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);
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,您正在复制该值,因为“幻灯片”被设置为原始类型。试试这个:
然后
更改日志记录:
在这种情况下,您将看到您确实拥有对同一对象的引用。与其他一些语言 (C++) 不同,JavaScript 中无法说“请给我这个变量的别名”。
Yes, you're making a copy of the value, because "slide" is set to a primitive type. Try this:
and then
then change the logging:
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.
是正确的。由于您使用的是数字基元,因此变量包含值而不是指向它。变量仅在引用对象时才包含引用。
实现方法是使用对象属性并指向该对象 - 这正是
photoGalleryMod
及其slide
属性所具有的功能。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 itsslide
property.