I read a bit about the bind implementation in JS ( from John Resig's book ) :
It looks something like this : ( jsbin)
#1Function.prototype.bind = function ()
#2{
#3 var fn = this,
#4 args = Array.prototype.slice.call(arguments),
#5 object = args.shift();
#6
#7 return function ()
#8 {
#9 return fn.apply(object, args.concat(Array.prototype.slice.call(arguments)));
#10 };
#11 };
And I can test it like this:
var myObject = {};
function myFunction()
{
return this == myObject;
}
//---------
if (!myFunction()) alert("Context is not set yet"); //not set ye
var bindedFunction= myFunction.bind(myObject)
if (bindedFunction()) alert( "Context is set properly"); //set properly
//---------
However I have 2 question about the it :
Question #1
In Line #3 , the this is referes to the function which is executed , correct ? but isn't this suppose to be : "the object which holds the function" ?
If I do alert(this) inside the bind function , I see this :
function myFunction()
{
return this == myObject;
}
Question #2
In line #9 , Why does the returned function is
return function ()
{
return fn.apply ...
};
and not
return function ()
{
fn.apply ...
};
I dont understand it :
the returned function creates a closure and should return a function which is only executing fn.apply(o....
I don't understand why it returns additional return : like in return fn.apply(o....
returnreturns whatmyFunctionreturns