The use of the JavaScript method call () and apply ()

Source: Internet
Author: User

first on the code :

Example of the Apply () method

/*Define a human*/  functionPerson (name,age) { This. name=name;  This. age=Age ; }  /*define a student class*/  functionStudent (name,age,grade) {person.apply ( This, arguments);//arguments namely ["Zhangsan", 21, "first Grade"]     This. grade=grade; }  //create an instance of a student classvarStudent=NewStudent ("Zhangsan", 21, "first Grade")); //TestConsole.log ("Name:" +student.name+ "\ n" + "Age:" +student.age+ "\ n" + "Grade:" +Student.grade); /*result output: Name:zhangsan age:21 Grade: First grade*/

Call () Method Example-1:

/*Define a human*/  functionPerson (name,age) { This. name=name;  This. age=Age ; }  /*define a student class*/  functionStudent (name,age,grade) {Person.call ( This, Name,age);  This. grade=grade; }  //create an instance of a student classvarStudent=NewStudent ("Zhangsan", 21, "first Grade")); //TestConsole.log ("Name:" +student.name+ "\ n" + "Age:" +student.age+ "\ n" + "Grade:" +Student.grade); /*result output: Name:zhangsan age:21 Grade: First grade*/

Call () Method Example-2:

/*Define a human*/  functionPerson (name,age) { This. name=name;  This. age=Age ; }  /*define a student class*/  functionStudent (name,age,grade) {Person.call ( This, name);  This. grade=grade; }  //create an instance of a student classvarStudent=NewStudent ("Zhangsan", 21, "first Grade")); //TestConsole.log ("Name:" +student.name+ "\ n" + "Age:" +student.age+ "\ n" + "Grade:" +Student.grade); /*result output: Name:zhangsan age:undefined Grade: First grade*/

The use of the JavaScript method call () and apply ()

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.