在 JavaScript 中定义哈希成员的 setter
我有这样定义的哈希:
var props = {
id: null,
title: null,
status: null
};
我想为状态字段(并且仅针对它)定义设置器,如下所示:
props.__defineSetter__("status", function(val){
//Checking correctness of val...
status = val;
});
但它不起作用:( 那么,正确的做法是什么?
I have hash defined like this:
var props = {
id: null,
title: null,
status: null
};
I'd like to define setter for status field (and only for it) doing it as following:
props.__defineSetter__("status", function(val){
//Checking correctness of val...
status = val;
});
But it doesn't work :(
So, what's the right way to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
很简单,您需要使用
否则您只是将一个不相关的全局变量
status
设置为等于val
。正如已经指出的,setter/getter 并未在 IE 中实现。
另外,我不确定拥有一个与其设置的属性同名的设置器是否明智。不确定这是否会导致冲突,但这似乎是一个坏主意,是吗?理想情况下,要设置的变量应该隐藏在闭包中
,这样,status 就可以完全防止直接访问,这就是使用 setter 和 getter 的要点。
Simple, you need to use
Otherwise you are just setting an unrelated global variable
status
equal toval
.And as already noted, setters/getters are not implemented in IE.
Also, I'm not sure about how wise it is to have a setter that is the same name as the property it sets. Not sure if this will result in a conflict, but it does seem like a bad idea yes? Ideally the variable that would be set should be hidden in a closure
This way,
status
is fully protected from direct access, which is the point of using setters and getters.首先是MooGoo所指出的。而且,您不能使用与对象中现有变量相同的名称将属性设置器分配给对象。
所以你的代码必须是围绕这个的:
[编辑]
是的,MooGoo 编辑他的答案的速度比我写这个 8(.
The first thing is what MooGoo has pointed out. But also, you can not assign a property setter to an object using the same name as an existing variable in the object.
So your code would have to be something arround this:
[edit]
Yeah, MooGoo eddited his answer faster then time time I took to write this 8(.
这应该有效:
用法:
This should work:
Usage: