Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explaining some of John Resig's ninja code

Tags:

javascript

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)));
      };
};


var myObject = {};
function myFunction(){
    return this == myObject;
}
assert( !myFunction(), "Context is not set yet" );
var aFunction = myFunction.bind(myObject)
assert( aFunction(), "Context is set properly" );

Tiny modification to Jeffery's code below helped me understand the arguments used in the inner anonymous function. I just changed the 3 lines below

var introduce = function(greeting) { alert(greeting + ", my name is " + this.name + " ,home no is " + arguments[1]); }

hiBob(" 456"); // alerts "Hi, my name is Bob"
yoJoe(" 876");  

Thanks everyone

like image 750
Susan Avatar asked Oct 01 '09 23:10

Susan


3 Answers

The arguments object is an array-like object, it has only the length property.

Calling the slice function through the Array.prototype is a common technique to convert it to an array, so you will be able to use array functions like shift and concat on this example, directly.

like image 166
Christian C. Salvadó Avatar answered Nov 07 '22 17:11

Christian C. Salvadó


Array.prototype.slice.call(arguments) creates an Array containing all the arguments passed to the function.

like image 26
Alex Barrett Avatar answered Nov 07 '22 17:11

Alex Barrett


This code creates a new method on the Function type named bind that accepts a free function as input and returns a wrapper function that calls it as if it were a method on the specified object. This is quite similar to how a .Net delegate wraps together a function and its associated this reference.

Additionally, if more than one argument is supplied to bind, these additional arguments are prepended to the call -- this technique is also called currying.

To try to explain it in a simpler fashion, consider something like this:

var bob = { name: "Bob" };
var joe = { name: "Joe" };

var introduce = function(greeting) { alert(greeting + ", my name is " + this.name); }

var hiBob = introduce.bind(bob, "Hi");
var yoJoe = introduce.bind(joe, "Yo");

hiBob(); // alerts "Hi, my name is Bob"
like image 6
Jeffrey Hantin Avatar answered Nov 07 '22 18:11

Jeffrey Hantin