javascript multidimensional object

扶醉桌前 提交于 2020-02-02 03:06:55

问题


I'm trying to define a multidimensional object in JavaScript with the following code:

function A(one, two) {
    this.one = one;
    this.inner.two = two;
}

A.prototype = {
    one: undefined,
    inner: {
        two: undefined
    }
};
A.prototype.print = function() {
    console.log("one=" + this.one + ", two=" + this.inner.two);
}

var a = new A(10, 20);
var b = new A(30, 40);
a.print();
b.print();

The result is:

one=10, two=40
one=30, two=40

, but I expect

one=10, two=20
one=30, two=40

What am I doing wrong? Is a variable inner a class variable, not an instance?

JavaScript engine: Google V8.


回答1:


Because the object literal for inner gets shared for all instances. It belongs to the prototype and thus every instance shares the same object. To get around this, you can create a new object literal in the constructor.




回答2:


The inner part is a global object not bound to one instance.



来源:https://stackoverflow.com/questions/5940275/javascript-multidimensional-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!