javascript--Four function call forms

Source: Internet
Author: User
Tags object object

The purpose of this article is to analyze the four invocation forms of the function, to clarify the meaning of this in the function, to define the process of constructing the letter object, and to use the context to invoke the function.

In JavaScript, a function is a first-class citizen, and the function is a data type in JavaScript, not just as a module, as in C # or other descriptive languages. The function has four invocation patterns, namely: function call Form , method invocation form, constructor form, and apply form . Here all the calling patterns, the main difference in The meaning of the keyword this. The following are the different invocation forms.

One, function call form

The function invocation form is the most common form and is also the best understood form. The so-called function form is the general declaration of functions directly after the call is. For example:

1 // declares a function and calls the 2 function func () {3       alert (' Hello world!! ' );       4 }5 func ();

Or

1 // to define a function using a lambda expression of a function 2 var function () {3      alert ("Hello world!!" ); 4 }5 func ();

Both of these codes will pop up a dialog box that displays the text in the string. This is the function call.

You can see that the function calls are simple, just like the usual learning. The key here is that in the function invocation pattern, the This keyword in the function refers to the global object, if it is the Window object in the browser. For example:

1 var function () {2        alert (this);   3 }4 func ();

At this point, a dialog box pops up to print [object Window]

Second, method invocation mode

The function invocation pattern is simple and is the most basic way to call. But the same is true of functions, which are assigned to the members of an object and are not the same. After assigning a function to a member of an object, this is not called a function, but

should be called methods. For example:

1  //Define a function2  varFunc =function() {3Alert ("Am I a function?"));4 };5  //Assign it to an object6  varn \ {};7O.fn = func;//notice there's no parentheses here .8  //called9O.fn ();

at this point, O.fn is the method, not the function. In fact, the method body of FN is exactly the same as Func, but this there is a subtle difference. Look at the following code:

1  // connect the code above 2 alert (O.fn = = = func);

The print result is true, which indicates that two functions are the same thing. But modify the code of the function:

1  //Modify function Body2 varFunc =function() {3Alert This);4  };5  varo = {};6O.fn =func;7  //Compare8Alert (O.fn = = =func);9  //calledTen func (); OneO.fn ();

The result here is that two functions are the same, so the printing result is true. But because of the two function calls is not the same as Func's call, which prints [object Window], and O.fn's print result is [Object Object].

Here is the difference between a function call and a method call. In a function call, this refers to the Global object window, whereas in a method this refers to the current object. This refers to the object o in O.fn.

Third, constructor invocation pattern

Similarly, in a simple function mode, this represents window; In object method mode, this refers to the current object. In addition to both cases, a function in JavaScript can also be a constructor. Use a function as a constructor The syntax to use is to precede the function call with a new keyword. such as code:

1 //define a constructor2  varperson =function() {3       This. Name = "Preach Intelligence podcast";4      This. SayHello =function() {5Alert ("Hello, here is" + This. Name);6     };7 };8  //call the constructor to create the object9  varp =NewPerson ();Ten  //Working with Objects OneP.sayhello ();

The above case first creates a constructor person, and then uses the constructor to create the object P. This uses the new syntax. The SayHello () method is then called using the object. This is a simple case of using constructors to create objects . As you can see from the case, this refers to the object itself.

In addition to the simple use above, there are several changes to the function as a constructor. The following were:

  1. All attributes that need to be used by the object must be guided with this.

2, the return statement meaning of the function is rewritten, if the non-object is returned, this is returned;

3.1 This in the constructor

We need to analyze the process of creating objects in order to know the meaning of this. As in the following code:

1 var function () {2     this. Name = "Hello cc!!" ; 3  }; 4  var New Person ();

Here the function person is defined first and the entire execution is analyzed below:

1, the program in the execution of this sentence, the function body will not be executed, so the JavaScript interpreter does not know this the contents of the function.

2, next executes the new keyword, creates the object, the interpreter opens up the memory, obtains the object reference, the new object's citation used to give to the function.

3, immediately after the execution function, will pass over the object reference to this that is, in the construction method, this is the the object that was just created by new.

4. Then add members to this, that is, add members to the object.

5, the last function ends, returns this, the this to the left of the variable.

in the analysis of a structure letter after the execution of the number, you can get the constructor This is the current object.

3.2 Return in the constructor

The meaning of return in the constructor has changed, first if in the constructor, if an object is returned, the original intent is preserved. If the returned non-object, such as a number, Boolean, and string, then return this, as

If there is no return statement, this is also returned. Look at the following code:

1  //returns the return of an object2  varCTR =function() {3       This. Name = "CC";4      return {5Name: "XX"6      };7 };8 //Creating Objects9  varp =NewCtr ();Ten  //access the Name property Onealert (p.name);

executes the code, and the result here is "XX". Because an object is returned in the construction method, the return is preserved , the return content is the object after return. Look at the following code:

1 //to define a constructor that returns non-object data2  varCTR =function() {3       This. Name = "CC";4      return"XX";5  };6  //Creating Objects7  varp =NewCtr ();8  //Use9 alert (p);Tenalert (p.name);

The result of the code is that the pop-up window prints [object Object] and then prints "CC". Because this return is a string, which is a primitive type, the return statement here is invalid and returns the This object. So the first one to print is [object Object] and the second one does not print undefined.

Iv. Apply Invocation Mode

In addition to the above three invocation modes, the function as an object and the Apply method and the call method can be used, this is the fourth invocation pattern, I call it the Apply mode.

First introduce the Apply mode, first of all, here the Apply mode can be used as a function, or as a method of use can be said to be a flexible use. First look at the syntax: function name. Apply (object, array of arguments);

Here to see the syntax is more obscure, or use a case to illustrate:

1, new two JS files, respectively, "Js1.js" and "js2.js";

2. Add code

3, running two pieces of code, you can find that the first file name attribute has been loaded into the Global object window; The name attribute in the second file is in the incoming object o. That is, the first equivalent to a function call, the second is quite to the method call.

1  //in the Js1.js file2  varFunc1 =function() {3       This. Name = "Hello cc!! ";4  };5Func1.apply (NULL);6 alert (name);7  //js2.js File8  varFunc2 =function() {9       This. Name = "Hello xx!! ";Ten  }; One  varo = {}; A func2.apply (o); -alert (o.name);

  The parameters here are the parameters of the method itself, but they need to be stored in the form of an array. such as code:

1 // An example of an array 2  var arr1 = [1,2,3,[4,5],[6,7,8]]; 3  // to expand it 4  var arr2 = Arr1.conact.apply ([], arr1);

Then introduce the call mode. The biggest difference between the call mode and the Apply mode is that the parameters in call do not use arrays. See the following code to make it clear:

1  //Defining Methods2 varFunc =function(name, age, sex) {3       This. Name =name;4       This. Age =Age ;5      This. Sex =sex;6  };7  //Creating Objects8  varo = {};9  //add members to an objectTen  //Apply Mode One  varP1 = func.apply (O, ["xx", 25, "male")]); A  //Call mode -  varP2 = Func.call (o, "xx", 25, "male");

The above code, the Apply mode and the call mode result is the same.

In fact, the use of Apply mode and call mode, you can control the meaning of this arbitrary operation, in the function of JS design pattern is widely used. A brief summary, JS in the function call there are four modes, namely: function, method, structure

and apply. And in these patterns, the meaning of this is: in the function this is the Global Object window, in the square The This in the method is the current object, in the constructor this is the object that is created, in the Apply mode this can be arbitrarily

Specified. If NULL is used in the Apply mode, it is the function pattern, and if the object is used, it is the method pattern.

                                     

javascript--Four function call forms

Related Article

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.