Javascript Custom Scope Binding Function
Solution 1:
Why is the return in _function.apply(scope, arguments); there? And what is it doing and what is being returned? I removed that return and it still works.
This is there in case you want to return a value. Currently your talk function is not returning any value so you don't need it. if you change your talk function to
eve = {
talk: function(greeting) {
return ( greeting + ", my name is " + this.name) ;
}.bind(alice) // <- bound to "alice"
}
console.log(eve.talk("hello"));
Now you will realize why return is required
Solution 2:
It returns the result of applying the original function (the one being bound). When you make _function.apply
, the _function
will be called with scope
as the context, so inside the function this
will always refer to the scope
.
The second parameter arguments
is there to pass all the arguments to the original function. And the return
statement is there to make sure that the value returned from the original function call will also be returned from the bound function call.
Solution 3:
In the return you simply return new function. You close the scope
and _function
in the scope of the returned anonymous function. It's called closure - all variables visible in the parent function (the one which return the anonymous one) are visible in the returned function.
Here is your example:
Function.prototype.bind = function(scope) {
var _function = this;
return function() {
return _function.apply(scope, arguments);
}
};
function foo() {
console.log(this.foobar);
}
var bar = {
foobar: 'baz'
};
foo = foo.bind(bar);
So now step by step: foo.bind(bar);
returns the function:
function() {
return _function.apply(scope, arguments);
}
_function
is foo
, scope
is the bind
argument - bar
. arguments
is something like an array (not exactly) which contains all arguments of a function, so by: foo()
, your this
will be the scope provided as first argument of apply
. If you use foo(1,2,3)
arguments will contain 1,2,3
.
The logged result will be baz
.
Post a Comment for "Javascript Custom Scope Binding Function"