In JavaScript, call apply and bind method in detail _ basic knowledge

Source: Internet
Author: User
Tags anonymous constructor event listener

In JavaScript, call, apply, and bind are the three methods of a function object, and this article will understand three methods in more detail with the application of several scenarios.

Call ()

The call () method invokes a function or method under the premise of using a specified this value and several specified parameter values.

When you call a function, you can assign a different this object. This refers to the current object, the first parameter of the call method.

With the call method, you can borrow a method from another object on one object, such as Object.prototype.toString.call ([]), or an array object borrows the method on the object.

Grammar Fun.call (thisarg[, arg1[, arg2[, ...)]]
Thisarg
The This value specified when the fun function is run. The following are some things to note

(1) Do not pass, or pass null,undefined, in the function of this point to the Window object
(2) passing the function name of another function, which in the function refers to a reference to the function, is not necessarily the true this value when the function is executed
(3) A value of the original value (numeric, String, Boolean) will point to the automatic wrapper object for the original value, such as String, number, Boolean
(4) Passing an object in the function that points to this object

Arg1, Arg2, ...
The specified argument list.

Example
Primary application Examples

function A () {
 //output function A of this object
 Console.log (this); 
}
Define functions B function
B () {} 

var obj = {Name: ' This is a cock wire '};//define Object obj
a.call ();//window
a.call (null);//window
a.call (undefined);//window
A.call (1);//number A.call (
");//string A.call
(true);//boolean
A.call (b);/function B () {}
A.call (obj);//object

Calling anonymous functions using the call method and specifying this for the context

In the following example, when the greet method is invoked, the this value of the method is bound to the I object.

function greet () {
 var reply = [This.person, ' is a lightweight ', this.role].join (');
 Console.log (reply);
}

var i = {function greet () {
 var reply = [This.person, ' is a lightweight ', this.role].join (');
 Console.log (reply);
}

var i = {person
 : ' Jslite.io ', role: ' Javascript library. '
};

Greet.call (i); 
Jslite.io is a lightweight Javascript library. Person


 : ' Jslite.io ', role: ' Javascript library. '
};

Greet.call (i); 
Jslite.io is a lightweight Javascript library.

Calling anonymous functions using the call method

In the following example, in the For loop body, we create an anonymous function and then execute the anonymous function with each array element as the specified this value by calling the function's call method. The main purpose of this anonymous function is to add a print method to each array element object, which prints out the correct index number of each element in the array. Of course, it is not necessary to have the array element pass into that anonymous function as the this value (normal arguments can), in order to demonstrate the use of call.

var animals = [
 {species: ' Lion ', Name: ' King '},
 {species: ' Whale ', Name: ' Fail '}
];

for (var i = 0; i < animals.length i++) {
 (function (i) { 
 this.print = function () { 
 console.log (' # ' + i + ' + this.species + ': ' + this.name); 
 } 
 This.print ();
 }). Call (Animals[i], i);
}
#0 lion:king
//#1 Whale:fail

Calling function pass parameters using the call method

var a = {
 name: ' Jslite.io ',//define A's property
 say:function () {///define Method
 Console.log ("Hi,i ' m function a!");
 }
};
Function B (name) {
 Console.log ("Post params:" + name);
 Console.log ("I ' m" + this.name);
 This.say ();
}

B.call (A, ' test ');
Post params:test
//i ' m onepixel
//i ' m function A!

Apply ()

Syntax is almost identical to the syntax of the call () method, except that the second argument to apply must be an array (or class array object) that contains more than one argument. This feature of apply is important,

When you call an existing function, you can specify a this object for it. This refers to the current object, which is the object that is calling this function. With apply, you can write this method only once and then inherit it from another object without having to repeat the method in the new object.

Syntax: fun.apply (thisarg[, Argsarray])
Note: You need to note that Chrome 14 and Internet Explorer 9 still do not accept class array objects. If the class array object is passed in, they throw an exception.

Parameters
Thisarg

The Thisarg parameter of the call above.

Argsarray

An array or class array object in which the array elements are passed as separate arguments to the fun function. If the value of the parameter is null or undefined, no arguments need to be passed in. Class array objects can be used starting from ECMAScript 5.

Example

function Jsy (x,y,z) {
 console.log (x,y,z);
}

Jsy.apply (null,[1,2,3]); 
1 2 3

Example of using apply to link constructors

You can use apply to give an object link builder, similar to Java. In the next example we will create a global function function called construct to enable you to use a class array object instead of a parameter list in the constructor.

Function.prototype.construct = function (Aargs) {
 var fconstructor = this, 
 fnewconstr = function () { 
 Fconstructor.apply (this, Aargs);
 Fnewconstr.prototype = Fconstructor.prototype;
 return new Fnewconstr ();
};
function Myconstructor () {for
 (var nprop = 0; Nprop < arguments.length; nprop++) {
 Console.log s)
 this["property" + nprop] = Arguments[nprop];
 }
var myarray = [4, "Hello world!", false];
var myinstance = myconstructor.construct (myarray);

Console.log (myinstance.property1);  Logs "Hello world!"
Console.log (myinstance instanceof Myconstructor); Logs "true"
Console.log (myinstance.constructor);  Logs "Myconstructor"

Using apply and built-in functions

Smart apply usage allows you to use built-in functions in certain tasks that you would otherwise need to write to traverse an array variable. In the next example we use Math.max/math.min to find the maximum/minimum value in an array.

An array object with the maximum minimum number value in it
var numbers = [5, 6, 2, 3, 7];

/* Use Math.min/math.max in Apply * *
var max = Math.max.apply (null, numbers);
The general situation is to use Math.max (5, 6, ...) or Math.max (Numbers[0], ...) to find the maximum value
var min = Math.min.apply (null, numbers);

Usually we do this to find the number of the maximum or minimum value
//ratio to the top of the chestnuts, is not below the look is not comfortable above it?
max =-infinity, min = +infinity;
for (var i = 0; i < numbers.length i++) {
 if (Numbers[i] > Max)
 max = numbers[i];
 if (Numbers[i] < min) 
 min = numbers[i];


parameter array to be chopped and passed through

function Minofarray (arr) {
 var min = Infinity;
 var QUANTUM = 32768;

 for (var i = 0, len = arr.length i < len i + = QUANTUM) {
 var submin = Math.min.apply (null, Arr.slice (i, math.min (i + QUANTUM, Len));
 Console.log (submin, min)
 min = math.min (submin, Min);
 }

 return min;
}

var min = Minofarray ([5, 6, 2, 3, 7]);


Bind

The bind () function creates a new function (called a binding function)

Bind is a new method of ES5
The arguments are similar to call or apply
does not perform the corresponding function, call or apply will automatically perform the corresponding function
Returns a reference to a function
Grammar Fun.bind (thisarg[, arg1[, arg2[, ...)]]

The following example: when clicking on a Web page, the Eventclick is triggered to execute, outputting jslite.io p1 P2, indicating that this in Eventclick is changed to obj object. If you turn eventclick.bind (obj, ' p1 ', ' P2 ') into Eventclick.call (obj, ' p1 ', ' P2 '), the page will output directly jslite.io p1 P2

var obj = {name: ' Jslite.io '};
/**
 * Add click event Listener to document and bind Eventclick function
 * Set Eventclick as obj via the bind method and pass parameters p1,p2
* * Document.addeventlistener (' Click ', Eventclick.bind (obj, ' p1 ', ' P2 '), false);
Triggers and executes
function Eventclick (a,b) {
 console.log (
  this.name,//jslite.io
  A,//p1
  b//p2 when clicking on the Web page)
 )
}
Jslite.io p1 P2

Compatible

if (! Function.prototype.bind) {
 Function.prototype.bind = function (othis) {
 if (typeof this!== "Function") {
 // Closest thing possible to the ECMAScript 5
 //internal iscallable function
 throw new TypeError ("Function.prototyp E.bind-what is trying to be bound isn't callable ");

 var Aargs = Array.prototype.slice.call (arguments, 1), 
 Ftobind = this,//this points to the target function
 Fnop = function () {},
   fbound = function () {return
  ftobind.apply, this instanceof Fnop
   . This is the new obj
   : othis | | t his,//if the passed Othis is invalid, the caller of Fbound is merged as this
  
  //The parameter passed through bind and the parameters passed by the call, and is passed as the final parameter
  Aargs.concat ( Array.prototype.slice.call (arguments)));
 Fnop.prototype = This.prototype;
 Copy the target function's prototype object into the new function, because the target function may be used as a constructor to use
 Fbound.prototype = new Fnop ();
 Returns a reference to the Fbond, calling return Fbound on demand from outside;


Compatible examples from: Https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

Application Scenario: Inheriting

function Animal (name,weight) {
 this.name = name;
 This.weight = weight;
}
function Cat () {
 ///In call will this as the Thisargs parameter pass
 ///animal method to point to this in cat
 So this point in the animal is the Cat object
 ///The name and weight attribute defined in animal, which is equivalent to having the attribute defined in the cat with the attribute
 //cat object defined in the animal. Thus attaining the purpose of succession
 Animal.call (this, ' cat ', ') ';
 Animal.apply (this,[' cat ', ' m '));
 This.say = function () {
 console.log ("I am" + this.name+ ", my weight is" + this.weight);
 }
When cat is generated by the new operator, this in cat points to the Cat object
var cat = new Cat ();
Cat.say ();
Output => I am cat,my weight is 50

Prototype extension

Extend and customize methods on prototype functions, thus not polluting native functions. For example: We extend a forEach on the Array

function test () {
 //detects whether arguments is an instance of array
 console.log
 arguments instanceof array,//false
 Array.isarray (arguments)//false
 );
 Determine if arguments has a ForEach method
 Console.log (Arguments.foreach); 
 Undefined
 //apply ForEach in the array to arguments
 Array.prototype.forEach.call (arguments,function (item) {
 Console.log (item); 1 2 3 4
 });
Test (1,2,3,4);

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.