I have the following code inside my revealing module, but I am uncertain with how to declare/define imageListItem
, which is strictly a DTO and doesn't really require any information hiding. Am I correctly defining this object?
var imageListItem = function() {
var _title;
Object.defineProperty(this, "title", {
get: function () { return _title; },
set: function (value) { _title = value; }
}
);
};
var imageList = (function () {
var buffer = new CBuffer();
return {
populate: function (listItems) {
buffer.push(listItems);
},
rotate: function() {
buffer.rotateLeft();
}
}
})();
With imageListItem
, I want to declare an object structure for later use. That declaration should not logically be dependent on how that object will later be used. That is, I don't want to find myself dynamically assigning new properties to, or deleting properties from, imageListItem
by accident. Any assignment to properties should strictly be only to properties that have already been declared on the object.
Object.freeze()
almost accomplihses this, by preventing properties being added or removed, but it also prevents properties being changed.
E.g. I want this:
var obj = {
prop: function() {},
foo: 'bar'
};
// New properties may be added, existing properties may be changed or removed
obj.foo = 'baz';
obj.lumpy = 'woof';
var o = Object.freeze(obj);
// Now any changes will fail
function fail(){
'use strict';
obj.delete(foo); // throws a TypeError
obj.quaxxor = 'the friendly duck'; // throws a TypeError
}
I dont' want this:
// Now any changes will fail
function fail(){
'use strict';
obj.foo = 'sparky'; // throws a TypeError
}
You see? I want freeze
to prevent quaxxor
being added to obj
, but I don't want it to prevent me changing the value of foo
.
What you are looking for may be either
Object.preventExtensions()
orObject.seal()
.Similarly to
Object.freeze()
, both methods prevent new properties from being added to the object, nevertheless allow changing values of existing properties.The difference between
seal
andpreventExtensions
is thatseal
strictly disallows deletion and conversion of properties from/to data accessors, whilepreventExtensions
doesn't actually prevent existing properties from being deleted: this behavior depends on the JS engine you're using (some engines may let you delete the property, other ones may not).So basically, quoting from the MDN Documentation:
Here's an example to demonstrate the behavior of both methods:
Now, talking about your
ImageListItem
Object, you can achieve what you want simply adding a line of code: