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
dummy.nameAccessor = 'Mazinga';
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.
dummy.nameAccessor
不是一个函数,它是一个字符串name value is: empty
。
Your methods syntax is not correct, try :
var dummy = {
name: 'empty',
description: 'static description',
getName : function(){return 'name value is: ' + this.name;},
setName : function(value){ this.name = value;},
getDesc : function(){return 'description value is: ' + this.description;}
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.