The use of the call function and the Apply function in JavaScript

Source: Internet
Author: User

The use of the call function and apply in Javascript:

The call function and the Apply function in JavaScript are switches to the execution context, which is performed by switching a function from the currently executing context to another object, for example:

SourceObj.method.call (DESTOBJ,PARAMS1,PARAMS2) is the method function in Sourceobj is placed in the Destobj execution

The call function has another important role to play in JavaScript object-oriented programming, such as:

function ParentClass () {    this. Showtext (text) {        alert (text);    }}; function Inherentclass () {    Parentclass.call (this);}; var instance=New  inherentclass (); Instance.showtext (' inherent caller ');
View Code

Of course, it is possible to implement multiple inheritance in this way, just by invoking the call method with each parent class in the subclass.

The same applies and call functions, except that the parameters passed in are different, the first parameter in the argument list of the Apply function and the call function is the same, the second argument in the call function can be any argument, and the second argument of the Apply function must be an array. And the Apply function can only have 2 parameters.

Here's a quick demo of how to use the Apply function:

function Sourceobj (firstprams,secondparams) {    alert (firsparams+secondparams);} function Destobj (firstparams,seconparams) {    alert (firstparams*secondparams);} Sourceobj.apply (destobj,[6,2]);        // result=12
View Code

The use of the call function and the Apply function 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.