Array as protected Object property in JavaScript -



Array as protected Object property in JavaScript -

i'm trying build javascript constructor has array property read-only access:

var word = function() { var _occurrences = []; object.defineproperties(this, { "occurrences": { get: function() { homecoming _occurrences; } }, "addoccurence": { value: function(occ) { _occurrences.push(occ); } } }); };

the array private variable get-er pointing it.

var myword = new word(); myword.addoccurrence(123); var occ = myword.occurrences;

all works fine.

myword.occurrences = [];

is blocked, should be. surprisingly, works:

myword.occurrences.push(321);

protecting property keeps new assignments, not write access through array methods - though accessed through getter. makes object.defineproperty() rather pointless me.

object.freeze() / object.seal() not alternative need write access addoccurrences() method.

any ideas? have overlooked something?

javascript provides references objects (including arrays). when return _occurrences, homecoming reference array, can manipulate it.

if want prevent that, homecoming re-create of array instead.

return _occurrences.concat();

javascript arrays protected

Comments

Popular posts from this blog

model view controller - MVC Rails Planning -

ruby on rails - Devise Logout Error in RoR -

html - Submenu setup with jquery and effect 'fold' -