我的揭示模块中有以下代码,但我不确定如何声明/定义imageListItem
,这严格来说是一个 DTO,并不真正需要任何信息隐藏。我是否正确定义了这个对象?
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
,我想声明一个对象结构供以后使用。该声明在逻辑上不应依赖于该对象稍后将如何使用。也就是说,我不想发现自己动态分配新属性或从中删除属性,imageListItem
意外地。对属性的任何分配都应该严格只针对已在对象上声明的属性。
Object.freeze() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze通过防止添加或删除属性几乎可以实现这一点,但它也可以防止更改属性。
例如。我要这个:
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
}
我不想要这个:
// Now any changes will fail
function fail(){
'use strict';
obj.foo = 'sparky'; // throws a TypeError
}
你看?我想freeze
阻止quaxxor
被添加到obj
,但我不希望它阻止我改变的值foo
.