• Ic - ...dddooooh.. :(). Therefore, the proper usage is (see line 15);

    // .bind() working this way:
    var obj = 
    { id:"obj"
    , cnt: 0
    , meth:function() {
        if ("obj" == this.id) {
          console.log("'this' is 'obj':"); 
          console.log("id="+ this.id + " in invocation # " + (++this.cnt));
          if (this.cnt < 3) { setTimeout(this.meth,1); } // <--- 'OK'
        } else {
          console.log("'this' is (unexpectedly) NOT 'obj'"); 
        }
      }
    }; 
    obj.meth = obj.meth.bind(obj); // <--- adjusted
    function onInit() {
      obj.meth();
    }
    

    And the output confirms that .bind() works when 'properly' used:

              |_| http://espruino.com
     1v81 Copyright 2015 G.Williams
    >echo(0);
    =undefined
    >onInit()
    'this' is 'obj':
    id=obj in invocation # 1
    =undefined
    'this' is 'obj':
    id=obj in invocation # 2
    'this' is 'obj':
    id=obj in invocation # 3
    > 
    

    Alternative - to avoid the awkward redefinition / reassignment - and for the case of multiple intances, it is better to adjust line 10 as follows and to drop line 16 altogether:

          if (this.cnt < 3) { setTimeout(this.meth.bind(this),1); } // <--- 'BETTER'
    

    Drawback of this cleaner solution is the recreation of the bound function everytime... To avoid this, the bound function could be assigned as separate .methBound property and reused this way:

    ...
          if (this.cnt < 3) { setTimeout(this.methBound,1); } // <--- 'OK'
    ...
    ...
    obj.methBound = obj.meth.bind(obj); // <--- bind once
    ...
    
About

Avatar for allObjects @allObjects started