LJ Wadowski LJ Wadowski - 2 months ago 7
Javascript Question

Why two arrays are "equal" for getter when they have the same values?

I'd like to have a custom getter and setter method for my object which wraps

Map
.
Somehow when I use arrays as a key
getter
behaves as they are equal when they have the same values. Even though they are two different references. (tested in FF and Chrome).

JSFIDDLE

var Cons = function (){
this.data = new Map();
};

Cons.prototype.initialiseGetterAndSetter = function initialiseGetterAndSetter(prop){
Object.defineProperty(this, prop, {
get: function(){
return this.data.get(prop);
},
set: function(val){
this.data.set(prop, val);
}
});
};

var obj = new Cons();

var arr1 = [1];
var arr2 = [1];
var arr3 = [2];

obj.initialiseGetterAndSetter(arr1);

obj[arr1] = 1;

document.getElementById('box1').innerText = obj[arr1]; // 1 as expected
document.getElementById('box2').innerText = obj[arr2]; // expected undefined but got 1
document.getElementById('box3').innerText = obj[arr3]; // undefined as expected


As you can see it doesn't matter if what you pass to the getter it the same reference which I was expecting. It only checks if it has the same values which is kind a strange for me. Could you explain me why it behaves that way?

Thanks in advance!

EDIT
When you access map directly it returns expected results.

Answer

Object property names can only be string values. When you call Object.defineProperty(), it will coerce your prop value to a string (in which case arr1 and arr2 are both coerced to the same value.

The same happens when you try to access the object properties using obj[arr1] and obj[arr2].

If you want your object to expose a map, then give it members that access that map. Object properties don't work the way you are trying to use them:

var Cons = function (){
  this.data = new Map();

  this.get = function (key) { return this.data.get(key); };
  this.set = function (key, value) { this.data.set(key, value); };
};


// further down...

obj.set(arr1, 1);
Comments