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.
A multidimensional array or object is one that has one or more nested arrays or objects as property values.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With