Question

I was reading the ECMAScript Standard, and came across the following passage (section 8.6):

A named accessor property associates a name with one or two accessor functions, and a set of Boolean attributes. The accessor functions are used to store or retrieve an ECMAScript language value that is associated with the property.

Assume I'm using Javasript, which follows the ECMAScript standard.

The standard says: associates a name with one or two accessor functions.

How might I implement a property of an Object in Javascript that has only one of these accessor functions? I.e., the getter accessor function?

For instance, storing a value permanently in an Object property without having the ability to change it. As far as I've been able to work it, Object properties seem to automatically come with both accessor functions.

Is Object.freeze() the only method of accomplishing this?

Était-ce utile?

La solution

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top