Simply talk about call and apply

Source: Internet
Author: User

Function.call () calls the function as a method of the object, for example: Function.call (Thisobj,args,........);

Thisobj the object that invokes function. In the function body, thisobj is the value of the keyword this. If this parameter is NULL, the global variable is used

Args ... Any number of parameters that are passed to the function.

Return value: Value of function

Example:

function Add (b) {Console.log (a+b);} function Sub (b) {Console.log (a-b);} Sub.call (Add,2,3);  // -1

Call () invokes the specified function functions as an object thisobj, passing the thisobj parameter in the argument list to it. The return value is the return value after the function is called. In the function body, the keyword this refers to the Thisobj object. Or, if thisobj is null. The global object is used.

Example:

function  Textcar () {this.color= ' red '; This.wheel=function () {alert (this.color);}   } function  Car () {this.color= ' Blue ';} var textcar=new textcar (); var car=new car (); TextCar.wheel.call (car);

In fact, you can understand that the function can be used as the calling method of the object we passed in. actually apply

and call the use of the wrong way, a little difference is that the second passed parameter is the specified parameter array. This is a simple way to understand how this function is used. In fact, the specific mechanism is still unclear. I want to correct

Simply talk about 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.