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
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.
Array.prototype.slice.call(arguments)
creates an Array
containing all the arguments passed to the function.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With