Simple understanding of call and apply in Javascript

Source: Internet
Author: User
A simple understanding of call in Javascript and the ability to apply javascript to object orientation was later added. For compatibility, many strange things were made,

Function Animal () {this. name = "Animal"; this. showName = function () {alert (this. name) ;}} function Cat () {this. name = "Cat";} var animal = new Animal (); var cat = new Cat (); // use the call or apply method to convert the showName () that originally belongs to the Animal object () the method is handed over to the object cat for use. // The input result is "Cat" animal. showName. call (cat, ","); // animal. showName. apply (cat, []);

Therefore, we can see that call and apply occur to dynamically change this. When an object does not have a method, but other methods include, we can use call or apply to operate with other object methods.


The dom Node Selected through document. getElementsByTagName is an array similar to array. It cannot apply methods such as push and pop in Array. We can use:
Var domNodes = Array. prototype. slice. call (document. getElementsByTagName ("*"));
In this way, domNodes can apply all the methods in Array.

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.