Apply and call in JavaScript

Source: Internet
Author: User

 

There is a call and apply method in JavaScript, which is basically the same, but it has a slightly different effect.

I. Method definition 1, call method

Syntax: Call ([thisobj[,arg1[, arg2[, [,. ArgN]]])

Parameter Thisobj Optional. The object that will be used as the current object. Arg1, Arg2,, ArgN options available. The method parameter sequence will be passed.

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. To be clear is actually to change the object's internal pointer, that is, to change the object's this point to the content. This is sometimes useful in the object-oriented JS programming process.

2. 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.

Ii. Examples of common cases 1:call application

Quoting a code snippet on the web, it is natural to understand it after running.

<input type= "text" id= "MyText" value= "input text" ><script> function Obj () {this.value= "Object!   ";}   var value= "global variable";   function Fun1 () {alert (this.value);} Window.   Fun1 ();  Global variable Fun1.call (window);  Global variable Fun1.call (document.getElementById (' MyText '));   Input text Fun1.call (new OBJ ());   Object! Window. Fun1 (); Global Variables </script>

The first parameter of the call function and the Apply method is the object to pass to the current object, and this inside the function. The arguments that follow are all arguments passed to the current object.

Run the following code:

<script> var func=new function () {this.a= "func"} var myfunc=function (x) {var a= "myfunc";       alert (THIS.A);   alert (x); } myfunc.call (func, "var");</script>

It is visible that Func and Var are ejected separately. Call the Func function first and replace the THIS.A in the MyFunc with This.a= "Func"; Then the "var" passed to the method myfunc parameter x is visible with Func and Var ejected respectively.

Both apply and call are the same in effect, but they differ in parameters.

The first parameter has the same meaning. The second argument: Apply passes in an array of parameters, which is the combination of multiple parameters into an array, and call is passed in as a call parameter (starting with the second argument).
such as Func.call (FUNC1,VAR1,VAR2,VAR3) corresponding to the wording of the Apply: Func.apply (Func1,[var1,var2,var3]), The benefit of using apply at the same time is that you can directly pass in the arguments object of the current function as the second parameter of apply.

Example 2: an inherited demo
Inherited demo function Base () {This.member = "dnnsun_member";    This.method = function () {window.alert (this.member);    }}function Extend () {base.call (this);    Window.alert (member); Window.alert (This.method);}

As can be seen from the above example, extend can inherit the methods and properties of base after call.

By the way, using apply in the JavaScript framework prototype creates a schema that defines the class, with the following implementation code:

var Class = {  create:function () {    return function () {      this.initialize.apply (this, arguments);}}  }

Parsing: From the code perspective, the object contains only one method: Create, which returns a function, the class. But this is also the constructor of the class, where initialize is called, and this method is the initialization function defined at the time the class is created. In this way, you can implement the class creation pattern in prototype

Example:

var vehicle=class.create (); vehicle.prototype={initialize:function (type) {this.type=type;    }, Showself:function () {alert ("This vehicle is" + this.type); }}var moto=new vehicle ("moto"); Moto.showself ();

Operation Result: Thisvehicle is Moto   

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

Output Result: 4

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.

Example 4:
function Animal () {  this.name = ' Animal ';  This.showname = function () {    alert (this.name);  }} function Cat () {  this.name = ' cat ';} var animal = new Animal (); var cat = new Cat ();//Use the call or Apply method to give the object cat the ShowName () method that originally belonged to the animal object.  //input result is "cat"  Animal.showName.call (Cat, ', ');//animal.showname.apply (cat,[]);

The output is: 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.

Example 5: Implementing Inheritance
function Animal (name) {  this.name = name;  This.showname = function () {    alert (this.name);  }} function Cat (name) {  Animal.call (this, name);} var cat = new Cat (' Black cat '); Cat.showname ();

The output is: Black Cat

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.

Example 6: Implementing Multiple Inheritance
var S1 = function (name) {  this.name = name;} var s2 = function (Sex) {  this.sex = sex;} var s3 = function (age) {  this.age = age;} var Student = function (name,sex,age,score) {  s1.call (this,name);  S2.call (this,sex);  S3.call (this,age);  This.score = score;} Student.prototype.construction = Student;var s = new Student (' Jack ', ' Male ', ' n ', ' s '); Console.log (s.name); Output: Jackconsole.log (s.sex);  Output: Male Console.log (s.age);  Output: 12console.log (S.score);//output: 100

In this way, we can separate different programmers according to different function modules, and finally merge them to achieve multiple inheritance.

Apply and call in JavaScript

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.