0

I get the error:

Uncaught TypeError: Cannot read property 'interval' of undefined

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?

1
  • 1
    Define "better". There are certainly other ways, but unless there are some criteria for evaluation (faster, easier to read, extensible, etc.), who is to say one is "better" than another except by subjective opinion? ;-) Commented Jul 25, 2015 at 0:04

2 Answers 2

1

No way.

But conceptually all you need is moving the constant one level up:

var defaultInterval = 5000;
var loop = {
    interval: defaultInterval,
    maxInterval: defaultInterval * 12
};
Sign up to request clarification or add additional context in comments.

Comments

0

One option is using self executing function.

var loop = (function () {
    var _ = {};

    _.interval         = 5 * 1000;
    _.maxInterval      = _.interval * 12;

    return _;
})();

1 Comment

Actually probably var loop = {}; loop.interval = 5 * 1000; loop.maxInterval = loop.interval * 12; is best.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.