You are reading a single comment by @Gordon and its replies. Click here to read the full conversation.
  • Glad you got this sorted - this is one of the classic JavaScript pitfalls. function() { ... } doesn't remember the value of this.

    The easiest way to think of it (I find) is that JS is dumb, and when you use this, JS looks back at how the function was called (and not the function itself):

    var a = {
     b :42,
     c : function() { print (this.b); }
    };
    
    a.c(); // prints 42
    a["c"](); // prints 42
    var z = a.c;
    z(); // doesn't work
    
    var somethingelse = {
     b :"uh oh",
     c : a.c
    };
    somethingelse.c(); // prints "uh oh"
    

    However arrow functions do remember the value of this so in your case if you did:

    SOUND.prototype.multibeep_works_not = function(freq,time,nr){
      setInterval(() => { this.beep(freq,time); }, 1000);
    };
    

    Then it'd work :/

  • Thanks for the follow up!

    I kinda realized JS is "dumb", but expected a behavior similar to other language and got frustrated.
    Oh well, at least I learned something.

    I'll try out the arrow functions.

About

Avatar for Gordon @Gordon started