6

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.

2
  • 1
    When thinking in JavaScript don't think in terms of instance think in terms of scope. Commented May 9, 2011 at 17:33
  • @Hogan, good point. It's important to remember that while JS has structures that look like classes, they're really first-class objects and need to be treated as such. Commented May 9, 2011 at 17:44

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

4 Comments

+1 : but could you please show the code to create the new object literal?
Basically the same thing just needs to be done in the constructor. this.inner = {two: two};
Yes, it solves my problem. But in this case, the code becomes less documented.
@ZeroDivisi0n, I see what you're saying, you could maybe move such an initialization to a init() method if that might help with documentation. It appears you're coding with class concepts, whereas JavaScript doesn't have classes. Your prototype at this point could just be A.prototype = {}. Think of using the prototype for stuff that you want to share between instances. Thus, you shouldn't look to it for exhaustive documentation of your "class" and every property that can exist on it. The constructor or init() function may be the best spot for listing these all out.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.