Before we begin, we define the person class:
function Person (name) {thisfunction() { Console.log (this. name);}
First, create a new person object:
var New Person (' Wenyi '//Wenyi
You can see that the output here is Wenyi, there's nothing to say, because this is pointing to the Wenyi object.
Next, I'll assign the say function to a variable, what happens?
var //Empty
You can see that the result of the output is empty, because after assigning to Func, this is the window, and Window.name is empty.
To change the point of this, we can use the apply method:
Wenyi
In the actual use, we often see this code:
$ (' button '). Click (function () { Wenyi. Say();});
- It's not beautiful because you have to nest multiple layers of function to solve this point problem.
- After assigning the say function to the Func variable as above, the transferred person does not use the original function correctly
Using the bind and Bindall functions is a good solution to the above problem:
var func = bind (Wenyi, Wenyi.say); func (); Wenyibindall (Wenyi, ' say '); var func = Wenyi.say;func (); Wenyi
So, how do you implement the Bind and Bindall functions?
function bind (obj, func) {return function () {return func.apply (obj, Array.prototype.slice.call (arguments)); };} function Bindall (obj) {var funcs = Array.prototype.slice.call (arguments, 1); for (var i = 0; i < funcs.length; i++) {obj[funcs[i]] = bind (obj, obj[funcs[i]); } return obj;
- Bind is implemented by using the Apply method
- The implementation of Bindall is to use bind to reassign all methods
Finally, attach a practical use to the complete example :
function person (name, age) { this.name = name; This.age = age; Bindall (This, ' sayname ', ' sayage ');} Person.prototype.sayName = function () { console.log (this.name);} Person.prototype.sayAge = function () { console.log (this.age);} var = new person (' Wenyi ', Wenyi); var func = Wenyi.sayname;func (); wenyi$ (' button '). Click (wenyi.sayage); 26
Note:
The above is a personal understanding, if there is inaccurate place, welcome to the relevant research counterparts.
For a complete implementation, please see the underscore source code.
Understand and implement the bind and Bindall functions in underscore