Object-oriented JS programming call and Apply methods

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. Definition of methods1. 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. The point is 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.

 Second, common examplesExample 1:call application Example

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

1<input type= "text" id= "MyText" value= "input Object" >2<script>3    functionOBJ () { This. value= "Obj Object";}4    varvalue= "Global variable";5    functionFUN1 () {alert ( This. value);}6 7Window. Fun1 ();//Global Variables8Fun1.call (window);//Global Variables9Fun1.call (document.getElementById (' MyText '));//Input ObjectTenFun1.call (NewOBJ ());//obj Object!  OneWindow. Fun1 ();//Global Variables A</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:

1<script>2   varFunc=New function(){ This. A= "Func"}3   varMyfunc=function(x) {4        varA= "MyFunc";5Alert This. a);6 alert (x);7    }8Myfunc.call (func, "Var");9</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:
  1  <script> 2  function   add (a, b)   3  {  4  alert (a + b);   "   6  function   Sub (A, b)   7  {  8  alert (a- b);   "  10  Add.call (Sub, 3, 1);  11  </script> 

Output Result: 4

The meaning of this example is that the Sub object executes the method in Add. Add.call (sub,3,1) = = Add (3,1), so the operation 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 3:
1<script>2 functionAnimal () {3    This. Name = ' Animal ';4    This. ShowName =function () {5Alert This. Name);6   }7 }8 functionCat () {9    This. Name = ' Cat ';Ten } One varAnimal =NewAnimal (); A varCat =NewCat (); - //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" theAnimal.showName.call (Cat, ', '); - //animal.showName.apply (cat,[]); -</script>

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, but the method of execution of the This object is cat,

So the this.name should be Cat.

Example 4: Implementing Inheritance
1<script>2 functionAnimal (name) {3    This. Name =name;4    This. ShowName =function () {5Alert This. Name);6   }7 }8 functionCat (name) {9Animal.call ( This, name);Ten } One varCat =NewCat (' Black Cat '); A cat.showname (); -</script>

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 5: an inherited demo
1<script>2 //Inherited Demos3 functionBase () {4      This. member = "Dnnsun_member";5      This. method =function() {6Window.alert ( This. Member);7     }8 }9 functionExtend () {TenBase.call ( This); One Window.alert (member); AWindow.alert ( This. method); - } -</script>

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:

1 var Class = {2   function  () {3     returnfunction () {4       this. initialize.apply (this, arguments); 5     }6  }7 }

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:

1 varvehicle=class.create ();2Vehicle.prototype={3Initializefunction(type) {4          This. type=type;5     },6Showself:function(){7Alert ("This vehicle is" + This. type);8     }9 }Ten varmoto=NewVehicle ("Moto"); OneMoto.showself ();

Operation Result: Thisvehicle is Moto  

Object-oriented JS programming call and Apply methods

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.