Call () and apply () in JavaScript

Source: Internet
Author: User

Yesterday just did Ali's front-end online pen question, which has a blank question as follows

function func () {  alert (this. valueOf ());  } func._________; // expected result is ABC

When I first saw this, I thought of the call () and the Apply () method, but the use of the two methods only had a vague memory.

So, for this problem, their own use of call () and apply () for further information and understanding, this record in order to deepen the impression, but also easy to find later.

Role:

Calls a function in a specific scope. That is, set the value of the This object in the function body.

Usage:

Both call () and apply () accept two parameters: one is the scope in which the function is run, and the other is the passed parameter.

The main difference between the two is that they receive parameters in different ways. where call () receives parameters, the parameters must be listed one at a time, and the parameter received by apply () must be an array of parameters, either an instance of an array or an arguments object. For example:

functionsum (num1,num2) {returnnum1+num2;} functionApplySum1 (num1,num2) {returnSum.apply ( This, arguments);//incoming Arguments Object}functionapplySum2 (num1,num2) {returnSum.apply ( This, [num1,num2]);//Incoming Array}functionCallsum (num1,num2) {returnSum.call ( This, num1,num2);//The incoming parameters are listed}

Whether you use call () or apply () depends entirely on what kind of method you take to pass parameters to the function.

So the answer to the blanks in the beginning is not the only one, here are the following two kinds:

Func.call ("abc"); Func.apply ("abc");

Call () and apply () 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.