Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript multidimensional object

Tags:

javascript

v8

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.

like image 973
ZeroDivisi0n Avatar asked May 09 '11 17:05

ZeroDivisi0n


People also ask

What is a multidimensional object?

A multidimensional array or object is one that has one or more nested arrays or objects as property values.

What is multidimensional array object?

A multidimensional array in MATLAB® is an array with more than two dimensions. In a matrix, the two dimensions are represented by rows and columns. Each element is defined by two subscripts, the row index and the column index.

Does JavaScript have multidimensional arrays?

JavaScript does not provide the multidimensional array natively. However, you can create a multidimensional array by defining an array of elements, where each element is also another array. For this reason, we can say that a JavaScript multidimensional array is an array of arrays.

How multidimensional array works in JavaScript?

Multidimensional arrays are not directly provided in JavaScript. If we want to use anything which acts as a multidimensional array then we need to create a multidimensional array by using another one-dimensional array. So multidimensional arrays in JavaScript is known as arrays inside another array.


1 Answers

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.

like image 188
Matt Molnar Avatar answered Sep 23 '22 21:09

Matt Molnar