setter

Inherited Accessor Property Can Only Be Overridden by Accessor Property

In Javascript, define a property prop as an accessor property via getter/setter:

1
2
3
4
var obj = {
get prop() {},
set prop() {}
};

And the property will have the following attributes:

> Object.keys(obj)
[ 'prop' ]
> Object.getOwnPropertyDescriptor(obj, 'prop')
{ get: [Function: prop],
  set: [Function: prop],
  enumerable: true,
  configurable: true }

Now, create a new object that inherits obj, and attempt to overwrite the accessor property by a data property:

1
2
var foo = Object.create(obj);
foo.prop = 'data';

But, the same property of the new object cannot be created:

> Object.keys(foo)
[]
> Object.getOwnPropertyDescriptor(foo, 'prop')
undefined

That is because that the property is an accessor property and it cannot be overridden by a data property. It can only be overridden by an accessor property:

1
2
3
4
5
6
Object.defineProperty(foo, 'prop', {
get: function prop() {},
set: function prop() {},
enumerable: true,
configurable: true,
});

Then, the foo object will have its own property named prop:

> Object.keys(foo)
[ 'prop' ]
> Object.getOwnPropertyDescriptor(foo, 'prop')
{ get: [Function: prop],
  set: [Function: prop],
  enumerable: true,
  configurable: true }

Getter and Setter Methods without Function Identifier Restriction

A JavaScript identifier must start with either a letter, underscore, or dollar sign:

1
2
3
4
5
6
7
8
> function 7/11(){}
SyntaxError: Unexpected number
> function '7/11'(){}
SyntaxError: Unexpected string
> var 7/11 = function(){}
SyntaxError: Unexpected number
> var '7/11' = function(){}
SyntaxError: Unexpected string

But object property does have such a limitation:

1
2
3
> var obj = { '7/11': function(){} }
> obj['7/11']
function (){}

And it works with accessor properties or getter and setter methods:

1
2
3
> var obj = { get '7/11'(){ return '7/11'; } }
> obj['7/11']
"7/11"

The syntax get '7/11'(){} looks like function '7/11'(){}, but it is not, getter and setter are still object properties. That is why it works. That’s another reason to use JavaScript object.