prototype bind support?

Posted on
  • Hi, my question kind of relates to my question from: generic pause/wait? I'm trying to wrap my head around how prototypeing works. does the Espruino support bind? For example:

    setTimeout(function (e) { this.getSensorReading(); }.bind(this), w); //Attempting to execute getSensorReading()

    I receive error:

    Uncaught Error: Function "bind" not found!
     at line 8 col 58
    ...this.getSensorReading(); }.bind(this), w); //Attempting to e...
    in function "getSensorResult" called from line 1 col 20
  • Hi - I'm afraid it doesn't support it yet... It's on my list though :)

    So the issue you have is that 'this' generally gets reset when you call setTimeout - however you can still access any other local variables. The easiest way around it (the one that I tend to use in examples/modules) is:

    var sensor = this;
    setTimeout(function (e) { sensor.getSensorReading(); }, w);
  • Works like a charm :)

  • @d0773d, @Gordon just most recently made .bind() work / implemented... see this conversation. Now you do not need the application defined anonymous function anymore, and the .bind() is more efficient in all ways.

  • @allObjects thanks for updating my post. I will definitely impliment bind().

  • As temporary work around on top of your file:

    Function.bind||(Function.prototype.bind=­function(c){var f=this,a=[],1);retu­rn function(){a.push.apply(a,arguments);ret­urn f.apply(c,a)}});

    In case you don't care about handling extra arguments ...

    Function.bind||(Function.prototype.bind=­function(c,f){f=this;return function(){return f.apply(c,arguments)}});

    Until it's solved, of course

  • Function.bind actually exists and works fine now, so hopefully you shouldn't need to do that...

  • Actually I've just realized Function.bind is there indeed but Function.prototype.bind is not ... but (function(){}).bind is there too ... oh well, good to know (sort of weird)

  • Yes, that's not right... Something strange is going on there - Thanks for letting me know.

    It still works though - I think it's just the way it appears.

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

prototype bind support?

Posted by Avatar for d0773d @d0773d