A detailed description of the apply and call functions in JavaScript

Source: Internet
Author: User

The first translation of technical articles, laughed at!


Translated original: Function.apply and Function.call in JavaScript


The first paragraph is slightly.

Each JavaScript function will have a number of subordinate (attached) methods, including ToString (), call (), and apply (). It sounds as if you're wondering if a function might have its own method, but remember that every function in JavaScript is an object. Take a look at this article and review (refresher) JavaScript features. You might also want to know the difference between functions and methods in JavaScript. I think the description of "function" and "method" is just a custom convention of JavaScript. Functions are based on themselves (for example, alert ()), and the method is a property of an object within the function (dictionary), and we invoke the method through the object. Each JavaScript object has a ToString () method, as illustrated by the code below, in a function object, we can use the ToString () method.
function foo () {alert (' X ');} Alert (foo.tostring ());
Because functions are objects, they have their own properties and methods. We can think of them as data. In this article, we only focus on the methods of the two functions apply () and call ().

Let's start with the following code:

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

We have defined a global function f (). F () accesses the variable x through the This keyword, but it is important to note that we cannot invoke this function from an instance of an object. What object does this point to? This will point to this global object. Our variable x is defined in this global object. The above code will work, and the result will display a dialog box displaying 10.

We can invoke call () and apply () through this. As the following example shows how to use Call ():

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

The first call to F () will display a 10 dialog box, as this is the point at which the global object is pointing. Then we invoke the call () method of the F function, the passed argument is O, and the result of the run shows the value of the X property in O of 15. The call () method uses its first argument as the this pointer to the F function. In other words, we will tell the runtime what object this is pointing to in the F function.

This jump sounds a bit comical, even for C + +, Java, and C # programmers. These are all interesting parts of the ECMAScript.

You can also pass parameters to a function via call ():

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

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

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 having to care about the parameters of the target method. This function can pass an additional parameter to the method by using 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! ']);
There's something wrong with this syntax. To invoke the Apply () method, we force the target function to use the parameters in the array. Fortunately, there is a way to make this syntax simpler. Before we do this, we must first introduce a: parameter identifier.

In JavaScript, in fact, each function has a variable-length argument list. This means that even if a function has only one parameter, we can pass 5 parameters to it. The following code does not have an error, 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 a property that represents length similar to an array.

function f (message) {//Message value and Arguments[0] are the same for (var i = 1; i < arguments.length; i++) {message + = Arguments[i];} alert (message);} The results show "Hello" f (' H ', ' e ', ' l ', ' l ', ' o ');

You should know that strictly speaking, arguments is not an array. Arguments has a length property, but there is no split, push, pop method. In the previous G () function, we can copy the required parameters from the arguments, make an array, and 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] = Funcvar args = [];for (var i = 2; I < Arguments.leng Th 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.



Document Information

    • Copyright Disclaimer: Free Reprint-Non-commercial-non-derivative-retain attribution | Creative Commons by-nc-nd 3.0
    • Original URL: http://blog.csdn.net/cdztop/article/details/37991535
    • Last modified: July 20, 2014 13:56

A detailed description of the apply and call functions 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.