The call () and apply () methods in JS are understood and used

Source: Internet
Author: User

1. Method definition Call Method:

Syntax: Obj.method.call (thisobj[,arg1[, arg2[, [,. ArgN]]])
Definition: A method of the Call object (obj) that replaces the current object (obj) with another object (Thisobj).
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 the new object specified by Thisobj (the This within the method points to the incoming 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

function Add (A, b) {
alert (this); 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);

Or a sub object to execute the Add method add this execution

Note: The function in JS is actually an object, and the function name is a reference to a function object.

var a = {        function(name) {            this. msg);        }    };     var b = {        ' Yjdgis '    };


A.myalert.call (b, ' Cloud gold land ');
A.ayalert.apply (b.[' Cloud gold land ');//The passed parameter is passed as an array

Execution results are: Cloud Gold: Yjdgis

The call () and apply () methods in JS are understood and used

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.