For these three methods, I think some people are still relatively unfamiliar.
So here's a simple introduction today ~
We can consider call () and apply () as a method of an object, calling the function indirectly by calling the method. The first argument to call () and apply () is to invoke the parent object of the function and get his reference through this in the body of the function.
Simple example:
function Test () { returnThis this. Y;} var o = {x:1,y:2};console.log (Test.call (o)); Console.log (Test.apply (o));
For Call (), all arguments after the first call to the context argument are the values to pass in the function to be called.
for apply (), its arguments are placed in an array.
Cases:
function Test (x, y ) {return x + y;} Console.log (Test.call(this,)); Console.log (test.apply (This, [2,3]));
I would like to go through these two examples, there should be a simple understanding of the two methods of call () and apply ().
Bind (): The primary function is to bind a function to an object. As the following example shows, when you call the Bind () method on the function f () and pass in an object o as a parameter, this method returns a new function. Calling the new function will invoke the original function f () as an O method. Any arguments passed into the new function are passed into the original function
function f (y) {returnthis. x+y}var o = {x:1}; var g = f.bind (o); g (// =>3
The bind () method in ECMAScript 5 does not just bind a function to an object, it also comes with some other effect: the arguments to the incoming bind () are bound to this, in addition to the first argument, and this accompanying application is a common functional programming technique, sometimes referred to as " Curry "(Wow, curry, sounds very tall on the bright ~)
varsum =function(x, Y) {returnx + y};//returns the and values of two arguments//creates a new function like sum, but the value of this is bound to null//and the first parameter is bound to 1, the new function expects to pass in only one argumentvarSUCC = Sum.bind (NULL, 1); SUCC (2)//=>3:x binds to 1 and passes in 2 as argument yfunctionF (y,z) {return This. x + y +z};//another function to do the additive calculationvarg = F.bind ({x:1},2); G (3)//= >6:this.x bound to 1,y bound to 2,z bound to 3
OK first introduced to here ~
Jane says call (), apply (), bind ()