[英]Initializing object properties with objects own properties
I get the error: 我收到错误:
Uncaught TypeError: Cannot read property 'interval' of undefined 未捕获的TypeError:无法读取未定义的属性“间隔”
When I try to initialize an object like this: 当我尝试初始化这样的对象时:
var loop = {
interval: 5 * 1000,
maxInterval: loop.interval * 12
};
So instead I have to do it like this: 因此,我必须这样做:
var loop = {
interval: 5 * 1000
};
loop.maxInterval = loop.interval * 12;
Is there a better way of doing this? 有更好的方法吗?
No way. 没门。
But conceptually all you need is moving the constant one level up: 但是从概念上讲,您所需要的只是将常量上移一级:
var defaultInterval = 5000;
var loop = {
interval: defaultInterval,
maxInterval: defaultInterval * 12
};
One option is using self executing function. 一种选择是使用自我执行功能。
var loop = (function () {
var _ = {};
_.interval = 5 * 1000;
_.maxInterval = _.interval * 12;
return _;
})();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.