I am playing with Javascript accessor properties (I am restarting from zero to study javascript), trying to create getter and setter for a simple object, here the code:
var dummy = {
name: 'empty',
description: 'static description',
get nameAccessor(){return 'name value is: ' + this.name;},
set nameAccessor(value){ this.name = value;},
get descAccessor(){return 'desccription value is: ' + this.description;},
};
console.log(dummy.nameAccessor);
console.log(dummy.nameAccessor('Mazinga'));
console.log(dummy.nameAccessor);
But it throws an error:
Uncaught TypeError: Property ‘nameAccessor’ of object # is not
a function
when it executes the setter code:
console.log(dummy.nameAccessor('Mazinga'));
What’s going wrong here?
EDIT:
Ok, it seems to be not a well-known feature of javascript, butI followed this example from
Javascript: Definitive Guide
var o = {
data_prop: value,
get accessor_prop() { /* function body here */ },
set accessor_prop(value) { /* function body here */ }
};
An accessor is not a function as a property of the object (“method”), but a function that is called when that property is assigned (set) or retrieved (get). Use
to invoke the setter function.
In contrast,
dummy.nameAccessor('Mazinga')gets the property “nameAccessor” (which results in the name string) and then tries to call it as a function, which will fail. It would work if your getter returned a function, but that is not what you want here.