Javascript multidimensional object

I am 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();

Result:

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 the variable innera class variable, not an instance?

JavaScript engine: Google V8.

+5
source share
2 answers

Because the literal object inneris shared for all instances. It belongs prototype, and therefore each instance has the same object. To get around this, you can create a new object literal in the constructor.

+5
source

A part inneris a global object that is not associated with a single instance.

0
source

All Articles