The difference between apply and call in Javacript

Source: Internet
Author: User

Apply: Methods can hijack another object's method, inheriting another object's properties. the accepted parameter is a string.

Call: Same as apply, except that the argument list is not the same. The parameter received is an array.

For example:

<script>= "Diz"= "song"var myObject = {firstName: "My", LastName: "Object"  function  helloname () {    Console.log (this. LastName, "Glad to Meet you! " ); } helloname.call (window); Helloname.call (myObject); </script> operation Result: Hello Diz song glad to meet! Hello my Object glad to meet

The Helloname method invokes the object property in window or MyObject.

<script type= "Text/javascript" >/*Define a human*/    functionPerson (name,age) { This. name=name;  This. age=Age ; }    /*define a student class*/functionstudent (Name,age,grade) {person.apply ( This, arguments);  This. grade=grade; }    //Create a Student class    varStudent=NewStudent ("Qian", 21, "first Grade")); //TestAlert ("Name:" +student.name+ "\ n" + "Age:" +student.age+ "\ n" + "Grade:" +Student.grade); //You can see the test results Name:qian age:21 Grade: First grade    //I did not assign a value to the name and age attribute in the student class, why is there the value of these two properties, this is the magic of apply.</script>

The difference between apply and call in Javacript

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.