I am reading this article – http://www.robertsosinski.com/2009/04/28/binding-scope-in-javascript/ – where a custom bind function is made.
Function.prototype.bind = function(scope) {
var _function = this;
return function() {
return _function.apply(scope, arguments);
}
}
alice = {
name: "alice"
}
eve = {
talk: function(greeting) {
console.log(greeting + ", my name is " + this.name);
}.bind(alice) // <- bound to "alice"
}
eve.talk("hello");
// hello, my name is alice
My question is this line in particlar
return function() {
return _function.apply(scope, arguments);
}
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
Now you will realize why return is required