How can I create an object of fixed structure?

前端 未结 1 1844
野的像风
野的像风 2021-01-15 12:26

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 r

相关标签:
1条回答
  • 2021-01-15 12:51

    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);
    };
    
    0 讨论(0)
提交回复
热议问题