The call, apply, bind method in JS

Source: Internet
Author: User

The call, apply, bind method one, call (), and apply () methods in JS

1. Method definitions
Call Method:
Syntax: Call ([thisobj[,arg1[, arg2[, [,. ArgN]]])
Definition: Invokes one method of an object, replacing the current object with another object.
Description
The call method can be used to invoke a method in place of another object. The call method can change the object context of a function from the initial context to a new object specified by Thisobj.
If the Thisobj parameter is not provided, then the Global object is used as the thisobj.

Apply method:
Syntax: Apply ([Thisobj[,argarray]])
Definition: A method of applying an object that replaces the current object with another object.
Description
If Argarray is not a valid array or is not a arguments object, it will result in a TypeError.
If none of the Argarray and Thisobj parameters are provided, then the Global object is used as a thisobj and cannot be passed any parameters.

2. Common examples

A

function Add (A, b)  {      alert (a+b);  }   function Sub (A, b)  {      alert (a-b);  }    Add.call (Sub,3,1);

The meaning of this example is to replace sub,add.call (sub,3,1) = = Add (3,1) with add, so the result is: alert (4); Note: The function in JS is actually an object, and the function name is a reference to a function object.

B

 function   Animal () { this . Name = "Animal" ;  this . ShowName = function   () {alert ( this  .name); }}  function   Cat () { this . Name = "Cat" ;  var  animal = new   Animal ();  var  cat = new  Cat (); 

Using the call or Apply method, the ShowName () method that originally belonged to the animal object is given to the object cat.
The input result is "Cat"
Animal.showName.call (Cat, ",");
Animal.showName.apply (cat,[]);
Call means to put the animal method on the cat, the original cat is no ShowName () method, now is to put the animal ShowName () method on the cat to execute, so this.name should be cat.

C. Implementing inheritance

function Animal (name) {          this. Name = name;             This function () {              alert (this. Name);          }      }           function Cat (name) {        Animal.call (this, name);    }           var New Cat ("Black cat");     Cat.showname ();

Animal.call (this) means that the Animal object is used instead of the this object, so there is no Animal of all the properties and methods in Cat, and the Cat object can directly invoke the Animal method and properties.

D, multiple inheritance

function Class10 ()  {      thisfunction(b)      {          alert (a-b);      }  }     function CLASS11 ()  {      thisfunction(b)      {          alert (a+b);      }  }     function Class2 ()  {      Class10.call (this);      Class11.call (this);  }

The

is simple, using two call to achieve multiple inheritance
of course, JS inheritance There are other methods, such as the use of the prototype chain, this is not the scope of this article, but here is a description of the use of call. Said call, of course, and apply, these two methods are basically a meaning, the difference is that the second parameter of call can be any type, and the second parameter of apply must be an array, or it can be arguments. The code is as follows:

var func=Newfunction() {this. a= "func"var myfunc=  functionvar a= "MyFunc"; alert (this + y);} myfunc.call ( Func,"var", "Fun"); //  myfunc.apply (func,["var", "Fun"]); // "Func" "var fun"
Second, bind

The method called bind is extended in ECMASCRIPT5 (ie6,7,8 not supported), using the following method

functionT (c) { This. id = "Object";  This. Dom = document.getElementById ("scroll");} T.prototype={init:function() {//①         This. Dom.onmouseover =function() {Console.log ("Over-->" + This. ID); }//②         This. Dom.onmouseout =function() {Console.log ("Out--" + This. ID); }. Bind ( This)    }};(NewT ()). Init ();

Results:

The effect of BIND is shown by the contrast of ① and ② and the result of the display: Changing the context of this

Bind is similar to call, for example, an acceptable parameter is divided into two parts, and the first parameter is the object that acts as this in the context of the function at execution time.
There are two of different points:
The return value of ①bind is a function
This is the context in which obj is used.

function func (name,id) {    console.log (name,id,this);} var obj = "look here";

Don't add anything.
Func ("", "--");

Using BIND is the function that returns the change context after this
var a = Func.bind (obj, "bind", "--");
A ();
Using call is to change the context of this and execute the function
var b = func.call (obj, "call", "--");
Results:

There are also differences in the use of parameters behind ②

function F (a,b,c) {    console.log (a,b,c);} var f_extend = F.bind (null, "extend_a")

F ("A", "B", "C")//This will output--a B C

F_extend ("A", "B", "C")//This will output--extend_a A B

F_extend ("B", "C")//This will output--extend_a B C

F.call (NULL, "extend_a")//This will output--extend_a undefined undefined

Call is to pass in the second and later arguments as an argument to the F method.
Bind, though, also gets the second and later arguments for subsequent execution of the method, but the arguments passed in the F_extend are based on the arguments passed in the bind.
This code is equivalent to the following operation
var f_extend = F.bind (null, "extend_a")

↓↓↓

var function (b,c) {    return f.call (null, "extend_a", B,c);}


To give a scenario: for example, there is now a way to do the processing according to different file types, and bind can create a simplified version of the processing method

function Filedealfunc (type,url,callback) {    if(type== "TXT") {...}     Else if (type== "xml") {...}    .....} var Txtdealfunc = Filedealfunc.bind (This, "txt");

It's more convenient to use.
Filedealfunc ("TXT", xxurl,func); Originally
Txtdealfunc (Xxurl,func); Right now

The following are compatible processing

if (! Function.prototype.bind) {    Function(obj) {        varthis             = arguments;         return function () {            1));     }}}

--------------------------------------------------------------------------------------------------------------- ----------------------

Finish

Reproduced must be reproduced in the words, the original author and the original post address.

Read MORE:

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

Http://www.jb51.net/article/61053.htm

http://www.zhangxinxu.com/wordpress/2012/10/ecmascript-es5-bind-array-slice-call-apply/

The call, apply, bind method in JS

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.