You can simply use get
sugar syntax:
var obj = {
get foo() {
return 1;
}
}
console.log(obj.foo) // 1
Or you can use Object.defineProperty:
var obj = {};
Object.defineProperty(obj, 'foo', {
get : function() { return 1; }
});
As you can see from the documentation linked, you can also specify a set of boolean attributes (the one mentioned in your question too), like writable
, enumerable
and configurable
; something that you can't do with just the first syntax I mentioned.
For example, you could also have:
var obj = {};
Object.defineProperty(obj, 'foo', {
value: 1,
enumerable: true
});
To obtain what you asking at the end of your question, and without using getter at all. Notice that in this way, you also prevent foo
property to be removed by delete
(by default, writable
and configurable
are false
, so in this way you're just sure that foo
property can be enumerate).
See the Object.defineProperty
documentation above for further details.