Before discussing the bind() method, let's first look at a question:
var altwrite = ;
altwrite("hello");
//1. What's the problem with the above code?
//2. What is the correct operation like
//How to implement() method
For the above question, the answer is not too difficult. The main test point is the problem pointed to by this. The altwrite() function changes this pointing to global or window objects, causing an abnormal call during execution. The correct solution is to use the bind() method:
(document)("hello")
Of course, you can also use the call() method:
(document, "hello")
The focus of this article is to discuss the implementation of the bind() method in the third issue. Before we start discussing the implementation of bind(), let’s take a look at the use of the bind() method:
Bind Function
The easiest way to use bind() is to create a function so that the function has the same value no matter how it is called. Common errors are like the example above, taking the method out of the object, then calling it, and want this to point to the original object. If no special treatment is done, the original object will generally be lost. Using bind() method can solve this problem beautifully:
= 9; var mymodule = { num: 81, getNum: function() { return ; } }; (); // 81 var getNum = ; getNum(); // 9, because in this example, "this" points to the global object // Create a function that binds 'this' to modulevar boundGetNum = (module); boundGetNum(); // 81
Partial Functions
Partial Functions are also called Partial Applications. Here is a section of definitions about partial functions:
Partial application can be described as taking a function that accepts some number of arguments, binding values to one or more of those arguments, and returning a new function that only accepts the remaining, un-bound arguments.
This is a good feature. Using bind() we set the predefined parameters of the function, and then pass in other parameters when calling:
function list() { return (arguments); } var list1 = list(1, 2, 3); // [1, 2, 3] // Predefined parameter 37var leadingThirtysevenList = (undefined, 37); var list2 = leadingThirtysevenList(); // [37] var list3 = leadingThirtysevenList(1, 2, 3); // [37, 1, 2, 3]
Use with setTimeout
Generally, this setTimeout() points to a window or global object. When using a class method, this needs to point to the class instance, you can use bind() to bind this to the callback function to manage the instance.
function Bloomer() { = (() * 12) + 1; } // Call declare function after 1 second = function() { ((this), 1000); }; = function() { ('I have ' + + 'Pece!'); };
Note: The above method can also be used for event handling functions and setInterval methods.
Bind function as constructor
Bind functions are also suitable for using the new operator to construct instances of the objective function. When using binding functions to construct an instance, note: this will be ignored, but the passed parameters are still available.
function Point(x, y) { = x; = y; } = function() { return + ',' + ; }; var p = new Point(1, 2); (); // '1,2' var emptyObj = {}; var YAxisPoint = (emptyObj, 0/*x*/); // Examples in the implementation are not supported,// Native bind support:var YAxisPoint = (null, 0/*x*/); var axisPoint = new YAxisPoint(5); (); // '0,5' axisPoint instanceof Point; // true axisPoint instanceof YAxisPoint; // true new Point(17, 42) instanceof YAxisPoint; // true
In the example above, Point and YAxisPoint share prototypes, so it is true when judged using the instanceof operator.
shortcut
bind() can also create shortcuts for functions that require a specific value of this.
For example, to convert an array object of a class into a real array, the possible examples are as follows:
var slice = ; // ... (arguments);
If you use bind(), the situation becomes easier:
var unboundSlice = ; var slice = (unboundSlice); // ... slice(arguments);
accomplish
In the above sections, you can see that bind() has many usage scenarios, but the bind() function was added in the fifth version of ECMA-262; it may not run on all browsers. This requires us to implement the bind() function ourselves.
First, we can simply implement the bind() method by specifying scope to the objective function:
= function(context){ self = this; //Save this, that is, the target function that calls the bind method return function(){ return (context,arguments); }; };
Considering the currying of the function, we can build a more robust bind():
= function(context){ var args = (arguments, 1), self = this; return function(){ var innerArgs = (arguments); var finalArgs = (innerArgs); return (context,finalArgs); }; };
This time the bind() method can bind objects and also supports passing parameters during binding.
Continue, Javascript functions can also be used as constructors. When bound functions are called in this way, the situation is more subtle, and it needs to be involved in the passing of the prototype chain:
= function(context){ var args = (arguments, 1), F = function(){}, self = this, bound = function(){ var innerArgs = (arguments); var finalArgs = (innerArgs); return ((this instanceof F ? this : context), finalArgs); }; = ; = new F(); return bound; };
This is the implementation of bind() in the book "JavaScript Web Application": by setting a relay constructor F, the bound function is on the same prototype chain as the function calling bind(). Use the new operator to call the bound function, and the returned object can also use instanceof normally. Therefore, this is the most rigorous implementation of bind().
In order to support the bind() function in the browser, you only need to modify the above function slightly:
= function (oThis) { if (typeof this !== "function") { throw new TypeError(" - what is trying to be bound is not callable"); } var aArgs = (arguments, 1), fToBind = this, fNOP = function () {}, fBound = function () { return ( this instanceof fNOP && oThis ? this : oThis || window, ((arguments)) ); }; = ; = new fNOP(); return fBound; };
The above brief analysis of the use and implementation of the bind() method in Javascript is all the content I share with you. I hope you can give you a reference and I hope you can support me more.