Defining non-write properties without Object.defineProperty?

So, I know you can do this:

var obj = {};
Object.defineProperty(obj, 'staticProp', {
    value: 'I will never change',
    writable: 'false'
});

      

And I know that you can do this:

var obj = {
    get gettableProp(){
        return 'gettable!'
    }
} 

      

Is it possible to declaratively describe non-rewritable / enumerable / custom properties rather than using Object.defineProperty () as you define a getter or setter?

I am asking because I have a function that receives an object like this:

ObjectProcessor({
    // A bunch of properties
})

      

I would really like to have this simple syntax for cases where I would like to include non-rewritable or non-enumerable properties, instead of doing

var obj = {}
Object.defineProperty(obj, 'staticProp', {
    value: 'I will never change',
    writable: 'false'
});
ObjectProcessor(obj);

      

+3


source to share


3 answers


Is it possible to declaratively describe non-rewritable / enumerable / custom properties rather than using Object.defineProperty () as you define a getter or setter?

Not.



(there is Object.defineProperties

, but I think that is not what you are looking for)

+4


source


No, there is no other method (except Object.defineProperties

and Object.create

) that allow you to provide several of these descriptors).

I would really like to have this simple syntax

Note that it Object.defineProperty

returns the passed object, so you can simplify your code to



ObjectProcessor(Object.defineProperty({}, 'staticProp', {
    value: 'I will never change',
    writable: 'false'
}));

      

and don't introduce this extra variable obj

.

+1


source


With a naming convention, you can create it in your ObjectProcessor:

var prefix = 'readonly_';

function ObjectProcessor(obj) {
    Object.keys(obj).filter(function (name) {
        // find property names which match your convention
        return name.indexOf(prefix) === 0;
    }).forEach(function (name) {
        // make the new property readonly
        Object.defineProperty(obj, name.substring(prefix.length), {
            value: obj[name],
            writable: false
        });

        // remove the old, convention-named property
        delete obj[name];
    });

    // remaining ObjectProcessor logic...
}

      

This allows us to handle writable and readonly properties:

ObjectProcessor({
    readonly_id: 1,
    name: 'Foo'
});

      

0


source







All Articles