开发者

javascript multidimensional object

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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜