javascript - Why two arrays are "equal" for getter when they have the same values? -
i'd have custom getter , setter method object wraps map
. somehow when use arrays key getter
behaves equal when have same values. though 2 different references. (tested in ff , chrome).
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 expected document.getelementbyid('box2').innertext = obj[arr2]; // expected undefined got 1 document.getelementbyid('box3').innertext = obj[arr3]; // undefined expected
as can see doesn't matter if pass getter same reference expecting. checks if has same values kind strange me. explain me why behaves way?
thanks in advance!
edit when access map directly returns expected results.
object property names can string values. when call object.defineproperty()
, coerce prop
value string (in case arr1
, arr2
both coerced same value.
the same happens when try access object properties using obj[arr1]
, obj[arr2]
.
if want object expose map, give members access map. object properties don't work way trying 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
Post a Comment