Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>For preserving the context, the <code>bind</code> method is really useful, it's now part of the recently released <a href="http://www.ecma-international.org/publications/standards/Ecma-262.htm" rel="noreferrer">ECMAScript 5th Edition</a> Specification, the implementation of this function is simple (only 8 lines long):</p> <pre><code>// The .bind method from Prototype.js if (!Function.prototype.bind) { // check if native implementation available Function.prototype.bind = function(){ var fn = this, args = Array.prototype.slice.call(arguments), object = args.shift(); return function(){ return fn.apply(object, args.concat(Array.prototype.slice.call(arguments))); }; }; } </code></pre> <p>And you could use it, in your example like this:</p> <pre><code>MyClass.prototype.myfunc = function() { this.element.click((function() { // ... }).bind(this)); }; </code></pre> <p>Another example:</p> <pre><code>var obj = { test: 'obj test', fx: function() { alert(this.test + '\n' + Array.prototype.slice.call(arguments).join()); } }; var test = "Global test"; var fx1 = obj.fx; var fx2 = obj.fx.bind(obj, 1, 2, 3); fx1(1,2); fx2(4, 5); </code></pre> <p>In this second example we can observe more about the behavior of <code>bind</code>.</p> <p>It basically generates a new function, that will be the responsible of calling our function, preserving the function context (<code>this</code> value), that is defined as the first argument of <code>bind</code>.</p> <p>The rest of the arguments are simply passed to our function.</p> <p>Note in this example that the function <code>fx1</code>, is invoked without any <em>object context</em> (<code>obj.method()</code> ), just as a simple function call, in this type of invokation, the <code>this</code> keyword inside will refer to the Global object, it will alert "global test".</p> <p>Now, the <code>fx2</code> is the new function that the <code>bind</code> method generated, it will call our function preserving the context and correctly passing the arguments, it will alert "obj test 1, 2, 3, 4, 5" because we invoked it adding the two additionally arguments, it already had <em>binded</em> the first three.</p>
 

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