Note that there are some explanatory texts on larger screens.

plurals
  1. POFunction.prototype.bind
    primarykey
    data
    text
    <p>I've got pretty interesting question about EcmaScript-5 Function.prototype.bind implementation. Usually when you use bind, you do it this way:</p> <pre><code>var myFunction = function() { alert(this); }.bind(123); // will alert 123 myFunction(); </code></pre> <p>Okay so that's cool, but what is suppose to happen when we do this?</p> <pre><code>// rebind binded function myFunction = myFunction.bind('foobar'); // will alert... 123! myFunction(); </code></pre> <p>I understand that it's completely logical behavior in terms of how Function.prototype.bind is implemented (<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind">https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind</a>). But in real life conditions it's completely useless behavior isn't it? The question is: is it bug or feature? If it's a bug, why it's nowhere mentioned? If it's a feature, why then Google Chrome with native "bind" implementation behaves absolutely the same way?</p> <p>To make it more clear, what in my opinion would make more sense, here is the code snippet that implements Function.prototype.bind a little bit differently:</p> <pre><code>if (!Function.prototype.bind) { Function.prototype.bind = function() { var funcObj = this; var original = funcObj; var extraArgs = Array.prototype.slice.call(arguments); var thisObj = extraArgs.shift(); var func = function() { var thatObj = thisObj; return original.apply(thatObj, extraArgs.concat( Array.prototype.slice.call( arguments, extraArgs.length ) )); }; func.bind = function() { var args = Array.prototype.slice.call(arguments); return Function.prototype.bind.apply(funcObj, args); } return func; }; } </code></pre> <p>So now try this:</p> <pre><code>// rebind binded function myFunction = myFunction.bind('foobar'); // will alert... "foobar" myFunction(); </code></pre> <p>In my opinion, replacing "this" makes more sense...</p> <p>So what do you guys think about it?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload