Let's look at a topic first.
var write = document.write;
Write ("Hello");
1. What's wrong with the above code
Could not execute correctly because the write function threw out the context, and this point to the Global or Window object, causing execution to prompt for illegal invocation of the exception, so we need to change the point of this
The right solution is to usebind/call/apply来改变this指向
Bind method
var write = document.write;
Write.bind (document) (' Hello ');
Call method
var write = document.write;
Write.call (document, ' Hello ');
Apply method
var write = document.write;
Write.apply (document,[' hello ']);
Bind function
The simplest use of bind () is to create a function so that the function has the same value, no matter how it is invoked. Common bugs like the example above, take the method out of the object and call it, and want this to point to the original object. If you do not do special processing, you will generally lose the original object. Using the bind () method is a nice way to solve this problem:
<script type= "Text/javascript" >
this.num = 9;
var module = {
num:81,
getnum:function () {
console.log (this.num);
}
};
Module.getnum (); Bayi, This->module
var getnum = module.getnum;
Getnum (); 9, This->window or global
var boundgetnum = getnum.bind (module);
Boundgetnum (); 81,this->module
</script>
Partial function (Partial functions)
Partial functions is also called Partial applications, where a section on the definition of a partial function is intercepted:
Partial application can is 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 this is 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 the other parameters when we call:
<script type= "Text/javascript" >
function List () {return
Array.prototype.slice.call (arguments);
}
var list1 = list (1, 2, 3);
Console.log (List1);//[1, 2, 3]
//predefined parameters of Panax Notoginseng
var leadingthirtysevenlist = list.bind (undefined, Panax notoginseng);
var list2 = Leadingthirtysevenlist ();
Console.log (LIST2);//[Notoginseng]
var list3 = leadingthirtysevenlist (1, 2, 3);
Console.log (LIST3);//[1, 2, 3]
</script>
Used with settimeout or setinterval
In general, this point to settimeout () points to a window or global object. When you use a method of a class that requires this to point to a class instance, you can use BIND () to bind this to a callback function to manage the instance.
<script type= "Text/javascript" >
function Bloomer () {
this.petalcount = Math.ceil (Math.random () * 12) + 1;
}
Call Declare function
Bloomer.prototype.bloom = functions () {
window.settimeout (This.declare.bind (this), 1000) after 1 seconds;
Bloomer.prototype.declare = function () {
console.log (' I have ' + this.petalcount + ' petals! ');
var test = new Bloomer ();
Test.bloom ();
</script>
Binding functions as constructors
A binding function is also useful for constructing an instance of a target function using the new operator. When you use a binding function to construct an instance, note that this is ignored, but the incoming arguments are still available.
<script type= "Text/javascript" >
function Point (x, y) {
this.x = x;
This.y = y;
}
Point.prototype.toString = function () {
console.log (this.x + ', ' + this.y);
};
var p = new Point (1, 2);
P.tostring (); 1,2
var yaxispoint = Point.bind (null,10);
var axispoint = new Yaxispoint (5);
Axispoint.tostring (); 10,5
console.log (axispoint instanceof point);//True
Console.log (Axispoint instanceof); True
Console.log (new point) instanceof Yaxispoint);//True
</script>
In the example above, point and Yaxispoint share the prototype, so the instanceof operator is used to determine true
Transformation of Pseudo-array
Some of the above sections show that bind () has a lot of usage scenarios, but the bind () function was added to the fifth edition of ECMA-262, and it may not run on all browsers. This requires that we implement the bind () function ourselves.
First we can simply implement the bind () method by specifying the scope for the target function:
Function.prototype.bind = function (context) {
self = this;//save this, that is, the target function of the Bind method called return function
() {
Return self.apply (context,arguments);
};
Given the function of Gerty, we can build a more robust bind()
:
Function.prototype.bind = function (context) {
var args = Array.prototype.slice.call (arguments, 1),
self = This ;
return function () {
var Innerargs = Array.prototype.slice.call (arguments);
var Finalargs = Args.concat (Innerargs);
Return self.apply (Context,finalargs);
}; <br>}
This time the bind () method can bind the object and also support the argument when binding.
Continue, JavaScript functions can also act as constructors, so when a binding function is invoked in this way, the situation is more subtle and involves the delivery of the prototype chain:
Function.prototype.bind = function (context) {
var args = Array.prototype.slice (arguments, 1),
F = function () {},
self = this,
bound = function () {
var Innerargs = Array.prototype.slice.call (arguments);
var Finalargs = Args.concat (Innerargs);
Return self.apply (This instanceof F. This:context), Finalargs);
F.prototype = Self.prototype;
Bound.prototype = new F ();
return bound;
};
This is the implementation of BIND () in the JavaScript Web application: By setting a relay constructor F, the bound function is on the same prototype chain as the function that calls bind (), and the binding function is invoked with the new operator. The returned object also works with instanceof, so this is the most rigorous bind () implementation.
For the bind () function to be supported in the browser, you only need to modify the above function slightly:
Function.prototype.bind = function (othis) {
if (typeof this!== "function") {
throw new TypeError ("Function.prot Otype.bind-what is trying to be bound isn't callable ");
var Aargs = Array.prototype.slice.call (arguments, 1),
ftobind = this,
Fnop = function () {},
Fbound = function () {return
ftobind.apply
instanceof fnop && othis? this:othis | | window,
aargs.concat (ARRA Y.prototype.slice.call (arguments))
);
Fnop.prototype = This.prototype;
Fbound.prototype = new Fnop ();
return fbound;
};
The above analysis of JavaScript in the use and implementation of BIND () is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud-dwelling community.