For bind, I froze, this method is commonly used in jquery to add one or more event handlers for the selected element.
Check the manual, found that the role of BIND and Apply,call is similar to change the function of the execute context, that is, runtime when the This keyword point. However, the method of use is slightly different. A function can be executed later after bind.
var altwrite = document.write;altwrite ("hello");
The above program runs, will error: uncaught typeerror:illegal invocation Illegal call
The reason for the error is that this points to the problem, because altwrite points to the Windowd object, and write points to the Document object
We can modify the context of the Altwrite through bind (), point it to the document, and modify it as follows:
var altwrite = document.write;altwrite.bind (document) ("hello");
Of course, you can also use the call()
method:
" Hello ")
Binding functions
bind()
The simplest use is to create a function so that the function has the same this value regardless of how it is called.
Take the method out of the object and call it, and you want this to point to the original object. If you do not do special processing, you will generally lose the original object. The use bind()
of the method can be very beautiful to solve the problem:
This. num =9; varMyModule ={num:Bayi, Getnum:function () {return This. Num;}}; Module.getnum (); //BayivarGetnum =module.getnum;getnum ();//9, because in this example, "This" points to the global object//create a ' this ' function bound to modulevarBoundgetnum =Getnum.bind (module); Boundgetnum ();//Bayi
Used with the settimeout
setTimeout()
in general, this refers to the window or global object. When you use the method of a class to point to a class instance, you can use this to bind()
bind to the callback function to manage the instance.
function Bloomer () { This. Petalcount = Math.ceil (Math.random () * A) +1;}//call declare function after 1 secondsBloomer.prototype.bloom =function () {Window.settimeout ( This. Declare.bind ( This), +);}; Bloomer.prototype.declare=function () {Console.log ('I have'+ This. Petalcount +'Flower Petals!');};
Note: The above method can also be used for event handlers and SetInterval methods
The use and implementation of the bind () method in JavaScript