Uncaught Error: Function "foo" not found!

Posted on
  • what is wrong with my sample code - any comments ?

    online with WEB IDE

    var bla = {
      init : function() {
        console.log("bla.init");
        this.foo();
        this.bar();
      },
      foo : function() {
        console.log("bla.foo");
      },
      bar : function() {
        console.log("bla.bar");
      }
    }
    
    > bla.init();
    
    /* output 
    
    bla.init
    bla.foo
    bla.bar
    
    */
    
    

    with E.on(): Uncaught Error.....

    var bla = {
      init : function() {
        console.log("bla.init");
        this.foo();
        this.bar();
      },
      foo : function() {
        console.log("bla.foo");
      },
      bar : function() {
        console.log("bla.bar");
      }
    }
    
    E.on("init",bla.init)
    
    setTimeout(save,2000);
    
    
    /* output
    
    bla.init
    Uncaught Error: Function "foo" not found!
     at line 2 col 10
        this.foo();
             ^
    in function called from system
    
    */
    
  • You need to use bla.init.bind(bla) or function(){bla.init()}, not just bla.init.

    It's one of the 'gotchas' of JavaScript, and it's the same thing that happens for setInterval, setTimeout, or any callback.

    Basically, when you call a function, like bla.init(), the this variable gets set up to bla. However, if you just pass bla.init, you're basically doing this:

    var x = bla.init;
    x();
    

    In that case, x is just a function, that has no association with bla at all - so when you call it, this isn't set.

  • thanks !

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

Uncaught Error: Function "foo" not found!

Posted by Avatar for MaBe @MaBe

Actions