A summary of the call () and apply () methods in JavaScript

Source: Internet
Author: User

Some time ago in the process of using JavaScript encountered the problem of inheritance, by the way the call () and the Apply () method to understand.

Two methods in common: the two methods have the same effect and are used to change the object of the current function call, that is, to change the direction of this.

The difference between the two methods: the difference is that the two methods differ in the way they are transmitted, and apply accepts the array parameters, and call accepts continuous parameters.

Definition of the Apply () method:

Function.apply (Obj,args);

OBJ: This object replaces the This object that is pointed inside the function class.

Args: This is an array that is passed as a parameter to the function.

Example:

<script>functionIntro (name,age) { This. name=name;  This. age=Age ;  This. speak=function() {Console.log (' My name is ' + This. name+ '. ' + ' I am ' + This. age+ ' years old. '); }}functionIntroinh (name,age) {intro.apply ( This, arguments); }varlm=NewIntroinh (' liming ', 20); Lm.speak ();</script>

The code above does a simple inheritance application and also shows the role of apply ().

Definition of the call () method:

Function.call (obj,[param1[,param2[,... [, Paramn]]]) ;

OBJ: This object replaces the This object that is pointed inside the function class.

Params: This is a list of parameters.

Example:

<script>functionIntro (name,age) { This. name=name;  This. age=Age ;  This. speak=function() {Console.log (' My name is ' + This. name+ '. ' + ' I am ' + This. age+ ' years old. '); }}functionIntroinh (name,age) {//intro.apply (this,arguments);Intro.call ( This, name,age);//Compare the above apply () difference;}varlm=NewIntroinh (' liming ', 20); Lm.speak ();</script>

Here only a simple concept and application of the narrative, the specific application of the project also requires our further practice.

A summary of the call () and apply () methods 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.