javascript multidimensional object

2019-05-02 22:19发布

问题:

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.



标签: javascript v8