[英]Accessors: setter does not work
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:我正在使用 Javascript 访问器属性(我从零重新开始学习 javascript),试图为一个简单的对象创建 getter 和 setter,这里是代码:
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
未捕获的类型错误:对象 # 的属性“nameAccessor”不是函数
when it executes the setter code:当它执行 setter 代码时:
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好吧,这似乎不是 javascript 的一个众所周知的特性,但是我从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.调用setter函数。
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.相比之下,
dummy.nameAccessor('Mazinga')
获取属性“nameAccessor”(产生名称字符串),然后尝试将其作为函数调用,但会失败。 It would work if your getter returned a function, but that is not what you want here.如果您的 getter 返回一个函数,它会起作用,但这不是您在这里想要的。
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;}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.