About call and apply those things

Source: Internet
Author: User

1. Definition:

Call: Invokes one method of an object, replacing the current object with another object.

Apply: A method of applying an object that replaces the current object with another object.

2. Usage:

Call:call (Thisobj, arg1, arg2, ...); Description: Thisobj typically represents an object, and if the Thisobj parameter is not provided, the Global object will act as thisobj. The second argument begins, such as arg1 ... Arbitrary form parameters can be passed.

Apply:apply (Thisobj, [Argarray]); Description: Thisobj typically represents an object, and if the Thisobj parameter is not provided, the Global object will act as thisobj. The second argument must start with an array or arguments.

3. Difference:

The difference is in the second argument.

4. Personal Understanding:

In fact, the method of the previous object is applied to the latter object (the first parameter in parentheses). That is, it changes the pointer to this.

5, do not say anything, on a few simple code:

1             functionfunc1 (name) {2                  This. Name =name;3                  This. ShowName =function(){4Console.log ( This. Name);5                 }6             }7 8             functionFunc2 (name) {9                  This. name=name;Ten             } One  A             varObj1 =NewFunc1 ("Func1"); -             varObj2 =NewFunc2 ("Func2"); - obj1.showname (); theObj2.showname ();//Direct error, because there is no ShowName () method in Obj2 -Obj1.showName.call (OBJ2);//This allows the ShowName () method in the Obj1 to be used for OBJ2


6. To implement inheritance

1             functionfunc1 (name) {2                  This. Name =name;3                  This. ShowName =function(){4Console.log ( This. Name);5                 }6             }7 8             functionFunc2 (name) {9Func1.call ( This, name);Ten             } One  A             varObj2 =NewFunc2 ("Func2"); -Obj2.showname ();

About call and apply those things

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.