How can I create an object of fixed structure?

落爺英雄遲暮 提交于 2019-12-01 11:14:26

What you are looking for may be either Object.preventExtensions() or Object.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 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).

So basically, quoting from the MDN Documentation:

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.

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

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);
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!