Call a bind function (Function.prototype.bind) without a context argument

Is there a reason why it was not possible to NOT determine the first argument of the .prototype.bind function and save the context in which it is called.

I have a use case when it is very useful to do this, but it seems to pass null or undefined, since the first argument binds the output function to the window.

Another way of saying this means that, apparently, the current implementation of native bind does not allow you to not bind the context of the function and only bind the prefixes of the argument to the bound function.

Example:

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 on Google Chrome version 27.0.1453.116 m

+4
source share
1 answer

To do this, you need to create your own binding function. The main reason for having .bind() was to consider the non-lexically defined this . Thus, they did not provide any way to use it without installing this .

Here is a simple example that 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))); }; }; 

These are pretty bare bones and don't apply to a function called as a constructor, but you can add this support if you want.


You can also improve it to behave like a native .bind() , unless null or undefined is 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))); }; }; 
+2
source

Source: https://habr.com/ru/post/1488598/


All Articles