如何创建固定结构的对象? [英] How can I create an object of fixed structure?

查看:139
本文介绍了如何创建固定结构的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的显示模块中有以下代码,但是我不确定如何声明/定义imageListItem,它严格来说是DTO,实际上并不需要任何信息隐藏.我是否正确定义了该对象?

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();
        }
    }
})();

对于imageListItem,我想声明一个对象结构以备后用.该声明在逻辑上不应取决于该对象以后将如何使用.也就是说,我不想偶然发现自己为imageListItem动态分配新属性或从中删除属性.对属性的任何赋值都应严格仅对已在对象上声明的属性进行赋值.

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() 几乎通过防止添加或删除属性来实现此目的,但同时也可以防止更改属性.

Object.freeze() almost accomplihses this, by preventing properties being added or removed, but it also prevents properties being changed.

例如我想要这个:

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的值.

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() or Object.seal().

类似于Object.freeze(),这两种方法防止将新属性添加到对象中,但是仍然允许更改现有属性的值.

sealpreventExtensions之间的区别在于,seal严格禁止从数据访问器删除和转换属性,而preventExtensions实际上并未阻止删除现有属性:此行为取决于您正在使用的JS引擎(某些引擎可能会让您删除属性,而其他引擎则不允许).

The difference between seal and preventExtensions is that seal strictly disallows deletion and conversion of properties from/to data accessors, while preventExtensions 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).

因此,基本上,请引用MDN文档:

So basically, quoting from the MDN Documentation:

Object.preventExtensions()方法可防止将新属性添加到对象(即,防止将来对该对象进行扩展). [...] 请注意,一般而言,不可扩展对象的属性可能仍会被删除 .

The Object.preventExtensions() method prevents new properties from ever being added to an object (i.e. prevents future extensions to the object). [...] Note that the properties of a non-extensible object, in general, may still be deleted.

Object.seal()方法可密封对象,从而防止向其添加新属性并将所有现有属性标记为不可配置.只要可写,当前属性的值仍可以更改. [...] 尝试删除密封对象或向密封对象添加属性,或将数据属性转换为访问器,反之亦然.

The Object.seal() method seals an object, preventing new properties from being added to it and marking all existing properties as non-configurable. Values of present properties can still be changed as long as they are writable. [...] Attempting to delete or add properties to a sealed object, or to convert a data property to accessor or vice versa, will fail.

下面是一个演示这两种方法的行为的示例:

Here's an example to demonstrate the behavior of both methods:

var myFirstObj = { foo: 1 },
    mySecondObj = { bar: "baz" };

Object.preventExtensions(myFirstObj);
Object.seal(mySecondObj);

myFirstObj.foo = false; // Works fine
mySecondObj.baz = "hello"; // Works fine
delete myFirstObj.foo; // May work fine depending on your JS engine

(function() {
    'use strict';
    myFirstObj.qux = 'something'; // Throws a TypeError
    mySecondObj.qux = 'something'; // Throws a TypeError
    delete mySecondObj.foo; // Throws a TypeError
})();


现在,谈论您的ImageListItem对象,您只需添加一行代码即可实现所需的功能:


Now, talking about your ImageListItem Object, you can achieve what you want simply adding a line of code:

var ImageListItem = function() {
    var _title;
    Object.defineProperty(this, "title", {
        get: function () { return _title; },
        set: function (value) { _title = value; }
    });

    // Choose the one which fits your needs
    Object.preventExtensions(this);
    // or
    Object.seal(this);
};

这篇关于如何创建固定结构的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆