Call&apply method of JS Knowledge finishing

Source: Internet
Author: User

Functions in JavaScript are objects, as well as other JS objects, where call and apply are among the more important methods that can be used to invoke functions indirectly. These two methods allow explicit invocation of this value, which means that all functions can be used as methods of any object, even if the function is not a method of that object.

Call Method:
Syntax:call ([thisobj[,arg1[, arg2[, [,. ArgN]]])
Apply method:

Syntax:apply ([Thisobj[,argarray]])

The call and apply methods work the same, but from the above syntax, they pass in different parameters, the first parameter of the two methods is the object that needs to invoke the method (thisobj), the function requires the argument called method is a list of incoming, The Apply method needs to pass in an array as an argument.

Instance:

1         functionpeople (name, age) {2 3              This. Name =name;4              This. Age =Age ;5              This. ShowName =function () {6 7Console.log ( This. Name);8 9             }Ten         } One  A  -         functionStudent (name, age) { -  the              This. Name =name; -              This. Age =Age ; -              This. Showage =function () { -  +Console.log ( This. age); -             } +         } A  at  -             varPeople =NewPeople ("Peoplename", 20); -             varStudent =NewStudent ("Studentname", 10); -  -People.showName.call (student);//Output Studentname

In the above code, you can also use People.showName.apply (student), output or studentname.

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.