具有内部引用属性的 JavaScript 对象
我正在尝试创建一个具有一系列“从属”属性的全局对象,这些属性是从同一对象中的一个“主”属性的值派生的 - 类似于:
var x = 5;
var myObj = {
master : 17,
slave1 : this.master + x,
slave2 : (this.master / 2.2) + 1,
slave3 : Math.floor(this.slave2)
//etc.
};
我意识到这是非常错误的,但这个概念是那里。我想做的是随着 myObj.master
的更新而更新所有这些“从属”属性。最干净的方法是什么?每个从属值是否需要由在 myObj.master
更改时触发的某些事件处理程序显式设置...?
I'm trying to create a global object with a series of 'slave' properties that are derived from the value of one 'master' property in the same object - something like:
var x = 5;
var myObj = {
master : 17,
slave1 : this.master + x,
slave2 : (this.master / 2.2) + 1,
slave3 : Math.floor(this.slave2)
//etc.
};
I realize this is horribly wrong as is, but the concept is there. What I'd like to do is have all these 'slave' properties updated as myObj.master
is updated. What's the cleanest way to do this? Does each slave value need to be explicitly set by some event handler that fires when myObj.master
is changed...?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果您的目标不是 Internet Explorer 用户,请尝试使用 getter 和 setter。
实际操作:
产生输出:
此代码将永远在任何版本的 Internet Explorer 中运行,无论是过去、现在还是将来。但是,仍然可以使用 getSlaveX() 函数访问从值。
If you are not targeting Internet Explorer users, try using getters and setters.
In action:
produces the output:
This code will never work in any version of Internet Explorer, past, present or future. However, it the slave values can still be accessed using the
getSlaveX()
functions.您可能最好使用函数。
You would probably be best off using functions.
大卫的答案是一个选择,但如果您想缓存结果而不是每次都重新计算它们,请以相反的方式进行:
David's answer is one option, but if you want to cache the results instead of recalculating them every time, do it the other way round:
另一种选择是使用构造函数来构建对象,例如:
在上面的示例中,我使用
master
参数和对x
全局属性的引用,如果您在该范围内没有可用的x
,您还可以为其提供一个参数。您还可以通过几个步骤构建对象:
Another option can be to use a constructor function to build your object, e.g:
In the above example I use a
master
argument and a reference to thex
global property, if you don't havex
available in that scope, you could provide also an argument for it.You can also build your object in several steps:
您不想公开从站并允许设置它们,因为这会删除它们与主站的链接。所以它们应该是私有的。
You don't want to expose the slaves and allow them to be set since that would erase their link to master. So they should be private.
您可以使用
valueOf
和toString
来模拟 getter,但它有点笨拙。You could simulate getters using
valueOf
andtoString
, but it's a little unwieldy.