Reputation: 41
Is there a reason why were not able to "NOT" define the first argument to Function.prototype.bind and have it retain the context its being called in.
I have a use case where its very useful to do this however it seems like passing null or undefined as the first argument binds the output function to Window.
Another way of saying this means it seems the current implementation of native bind does not allow you to not bind the context of the function and only bind argument prefixes to the bound the function.
Ex:
var a = function() {
this.foo = function() { console.log(this) };
this.foo = this.foo.bind(undefined,1);
};
var b = new a();
b.foo(); // Logs Window instead of the instance b;
This was tested in Google Chrome Version 27.0.1453.116 m
Upvotes: 4
Views: 1264
Reputation:
You'll need to create your own binder function to do that. The main reason for having .bind()
was to deal with the non-lexically defined this
. As such, they didn't provide any way to use it without setting this
.
Here's a simple example you could use:
Function.prototype.argBind = function() {
var fn = this;
var args = Array.prototype.slice.call(arguments);
return function() {
return fn.apply(this, args.concat(Array.prototype.slice.call(arguments)));
};
};
This is pretty bare-bones, and doesn't deal with the function being invoked as a constructor, but you can add that support if desired.
You could also enhance it to behave like the native .bind()
unless null
or undefined
are passed as the first argument.
Function.prototype.argBind = function(thisArg) {
// If `null` or `undefined` are passed as the first argument, use `.bind()`
if (thisArg != null) {
return this.bind.apply(this, arguments);
}
var fn = this;
var args = Array.prototype.slice.call(arguments);
return function() {
return fn.apply(this, args.concat(Array.prototype.slice.call(arguments)));
};
};
Upvotes: 2