How to Use the apply and call functions in JavaScript _ jquery-js tutorial

Source: Internet
Author: User
This article is the translation of Function. applyandFunction. callinJavaScript. I hope to help you translate the technical article for the first time!

Original translated text:

Function. apply and Function. call in JavaScript

The first section is omitted.

Each JavaScript function has many attached methods, including toString (), call (), and apply (). It sounds strange to you. A function may have its own method, but remember that every function in JavaScript is an object. Let's take a look at this article and refresher's JavaScript features. You may also want to know the differences between functions and methods in JavaScript. I think the descriptions of "functions" and "methods" are just the conventions of JavaScript. Functions are based on themselves (for example, alert (), and the method is the attribute of an object inside the function (dictionary). We call methods through objects. Each JavaScript Object has a toString () method. The code below illustrates how to use the toString () method in a function object.

function foo(){ alert('x');}alert(foo.toString());

Because functions are all objects, they have their own attributes and methods. We can regard them as data ). In this article, we only focus on the two functions: apply () and call ().

Let's start with the following code:

var x = 10;function f(){ alert(this.x);}f();

We define a global function f (). F () uses the this keyword to access variable x, but note that we cannot call this function through an object instance. What object does this point? This will point to this global object. Our variable x is defined in this global object. The code above can run normally. A dialog box is displayed in the running result, and 10 is displayed in the dialog box.

We can use this to call () and apply (). The following example shows how to use call ():

var x = 10;var o = { x : 15};function f(){ alert(this.x);}f();f.call(o);

First, call f () to display the 10 dialog box, because this points to a global object. Then we call the call () method of the f function. The input parameter is o, and the running result shows the value of the x attribute in o 15. The call () method uses its first parameter as the this pointer of the f function. That is to say, we will tell the runtime which object the "this" in function f points.

This jump sounds a little funny, and it is even abnormal for C ++, Java, and C # programmers. These are all interesting parts of ECMAScript.

You can also pass parameters to the function through call:

var x = 10;var o = { x : 15};function f(){ alert(this.x);}f();f.call(o);

Apply () and call () are similar, but apply () requires that the second parameter must be an array. This array is passed to the target function as a parameter.

var x = 10;var o = {x : 15};function f(message) { alert(message); alert(this.x);}f('invoking f');f.apply(o, ['invoking f through apply']);

The apply () method is useful because we can create a function without worrying about the parameters of the target method. This function can pass additional parameters to the method through the second array parameter of apply.

var o = {x : 15};function f1(message1) { alert(message1 + this.x);}function f2(message1, message2) { alert(message1 + (this.x * this.x) + message2);}function g(object, func, args) { func.apply(object, args);}g(o, f1, ['the value of x = ']);g(o, f2, ['the value of x squared = ', '. Wow!']);

This syntax is a bit problematic. To call the apply () method, we force the target function to use parameters in the array. Fortunately, there is a way to make this syntax easier. Before that, we must first introduce a parameter identifier.

In JavaScript, each function has a variable-length parameter list. This means that even if a function has only one parameter, five parameters can be passed to it. The following code does not have errors and the result shows "H ".

function f(message) { alert(message);}f('H', 'e', 'l', 'l', 'o');

In f (), if we do not want to accept other parameters, we can use the keyword arguments. Arguments represents a parameter object, which has an attribute representing the length similar to an array.

Function f (message) {// The value of message is the same as that of arguments [0] for (var I = 1; I <arguments. length; I ++) {message + = arguments [I];} alert (message);} // The result shows "Hello" f ('h', 'E ', 'l', 'l', 'O ');

You should know that, strictly speaking, arguments is not an array. Arguments has a length attribute, but there are no split, push, or pop methods. In the previous g () function, we can copy the required parameters from arguments to form an array, and then pass the array to apply ().

var o = {x : 15};function f(message1, message2) { alert(message1 + ( this.x * this.x) + message2);}function g(object, func) { // arguments[0] = object // arguments[1] = func var args = []; for(var i = 2; i < arguments.length; i++) {  args.push(arguments[i]); } func.apply(object, args);}g(o, f, 'The value of x squared = ', '. Wow!');

When we call g (), we can pass additional arguments as parameters instead of stuffing the arguments into an array.

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.