DefineProperty
by JakobJingleheimer
JavaScript
function Factory() {
var $$private = {
name: 'Jacob',
locations: ['downtown', 'burnaby', 'new westminster'],
inventory: {
smartphones: ['iPhone', 'Nexus 5']
}
};
var public = {};
function doSomething(int) {
return int++;
}
Object.defineProperties(public, {
'store': {
configurable: false,
enumerable: true,
value: {},
writable: false
},
'doSomething': {
configurable: false,
value: doSomething
}
});
Object.defineProperties(public.store, {
'name': {
configurable: false, // persistent datatype & immortal
enumerable: true, // iterable in for…in
value: $$private.name,
writable: false // value cannot be changed
},
'locations': {
configurable: false,
get: function getLocations() {
return $$private.locations;
},
enumerable: true,
set: function setLocation(value) {
var type = typeof value;
console.log(type);
if (type === 'string') {
$$private.locations = value;
}
}
},
'inventory': {
configurable: false,
enumerable: true,
value: $$private.inventory
}
});
Object.seal(public.store); // new properties cannot be added
return public;
}
var factory = Factory();
console.log( factory );
console.log( factory.store );
console.log( factory.store.locations );
factory.store.foo = 'b';
console.log( factory.store );
factory.store.name = 'b';
console.log( factory.store );
factory.store.locations[0] = ['b'];
console.log( factory.store.locations );
factory.store.locations[1] = 'kitsilano';
console.log( factory.store.locations );
factory.store.inventory = { tablets:...