Reputation: 11
Function.prototype.bind = function() {
var $this = arguments[0];
return this.apply($this, Array.prototype.slice.call(arguments, 1));
};
Is it good enough to use in real-world application?
Upvotes: 1
Views: 128
Reputation: 6949
No. There are a few things I don't like about this code, and a few reasons why it won't work.
First, most people don't assign arguments that way. It takes up extra space for no extra effect. Only use the arguments variable if the variable names should change depending on the number of arguments/type of arguments. To assign $this
you should do..
Function.prototype.bind = function($this) {
Second, bind should return a function. Your's returns whatever this
returns. Your function acts more like a Function:call
then a Function:bind
.
What you need to do to fix it, is make it return a function that when run will return whatever the function returns.
Try this:
Function.prototype.bind = function($this) {
// `this` changes inside the function, so we have to give it a safe name.
var self = this;
return function () {
return self.apply($this, Array.prototype.slice.call(arguments, 1));
}
};
Also, more modern browsers have the ECMAScript 5 standard of this function built in. The function is written in plain JavaScript, so for older browsers, just include this code suggested by Mozilla:
if ( !Function.prototype.bind ) {
Function.prototype.bind = function( obj ) {
var slice = [].slice,
args = slice.call(arguments, 1),
self = this,
nop = function () {},
bound = function () {
return self.apply( this instanceof nop ? this : ( obj || {} ), args.concat( slice.call(arguments) ) );
};
nop.prototype = self.prototype;
bound.prototype = new nop();
return bound;
};
}
Upvotes: 4