0

I'm learning Javascript and I've come across something I don't understand. This is the part of my object code:

var monster =
{
    ...

    //is the animation starting?
    hiding: true,
    delayDuration: Math.floor(Math.random() * 60),
    currentDelay: this.delayDuration,


    ...
};

If I console.log (delayDuration) I get a value, but if I console.log (currentDelay) it says 'undefined'.

I don't understand why currentDelay doesn't take the value of delayDuration. Can someone please explain this?

edit: @Bergi why did you mark this as duplicate? I couldn't find my question answered somewhere else edit2: yup, it's a duplicate. At least now I know the words for what I was asking.

silvith
  • 290
  • 2
  • 14
  • 1
    `this` doesn't exist at that point as the object you're creating (per Bergi's apropos correction). I've always found [this explanation](http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html) to be very helpful. –  Nov 18 '14 at 09:21
  • Because this.delayDuration probably doesn't exist. "this" doesn't refer to the monster object, it refers to the context the code is running in, and it probably has no delayDuration property. This is not a peculiarity of the javascript "this", this kind of code wouldn't work in C# either, for example. – svinja Nov 18 '14 at 09:22
  • 2
    @JeremyMiller: There always exists a `this`. Only it doesn't point to the object (which does not yet exist) – Bergi Nov 18 '14 at 09:23
  • As Jamie rightly said, you can't use variable from the same object you're in the process of constructing. Try something like below var monster = { ... hiding: true, delayDuration: Math.floor(Math.random() * 60), currentDelay: Math.floor(Math.random() * 60), ... }; as you want same value for delayDuration and currentDelay! – skool99 Nov 18 '14 at 09:29
  • @JeremyMiller I'll try to read it, though usually when people feel the need to say things like 'it's very simple' and 'we simply do this and that' it means I often don't understand anything that's being said, because it's written for people who already understand the issue and not explained to people who don't. – silvith Nov 18 '14 at 09:35
  • I hate those clauses too -- they add nothing to the quality of the writing and are most often simply demeaning. Irritations aside, that article has been very helpful to me which is why I shared. –  Nov 18 '14 at 09:37

1 Answers1

2

At the point of object creation neither monster nor any of it's properties are defined. You can't use variable from the same object you're in the process of constructing.

Also, Javascript uses function scoping, which means that the value of this will either be the window object or will be scoped to the closest instance you're creating using new (or other instance creation techniques).

Jamie Dixon
  • 53,019
  • 19
  • 125
  • 162