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);
source to share
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)
source to share
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
.
source to share
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'
});
source to share