Four invocation patterns of functions in JavaScript

Source: Internet
Author: User

Understanding the functions of the four methods of invocation, can effectively help us to analyze and understandJavaScriptcode. But often people are not clear or understand the four call patterns, inJavaScriptin,function is a one -class citizen,function inJavaScriptis a data type in, rather thanlikeC #or other descriptive language just as a module to use.There are four invocation modes of the function,respectively is: 1, function call form2, method invocation form3, constructor invocation form4, the context invocation form (Apply,Pager) Here in all the calling patterns,The main difference is the keywordThe meaning of this.The following are the different invocation forms.

One, function call form

The function invocation pattern is the simplest and best understood pattern, that is, when a function is declared, a function call pattern is called directly. For example:

1 function fn () {2 console.log (this); 3 }4 fn ();//function invocation mode

The key here is that in the function invocation pattern, the This keyword in the function points to the global object, if it is the Window object in the browser. Previous code Execution Result:

Second, method invocation mode

It is also a function that assigns a value to a member of an object and is not the same. After assigning a function to a member of an object, the function should not be called a function but should be called a method. For example:

var func = function () {
Console.log (this);
}
var obj = {};
Obj.fn = func; Assigning a function to a member of an object
Console.log (func = = = Obj.fn);//Determine whether the method body is the same
Func (); Function call
Obj.fn (); Method invocation

At this point, the method body of Obj.fn and Func is the same, that is, Obj.fn===func is true. However, one difference here is that the result of Func () is the Window object, and the result of Obj.fn () is the object obj.

Thus, when a function is called as a method, the inside of the function is pointed to the current object.

Third, constructor invocation pattern

The function can be called as a constructor, thus creating a new object. The syntax at this point is to precede the function with a keyword new.

// define a constructor var function () {    this. Name = "Tom";       This function () {        Console.log (this. name);};    }; // call the constructor to create the object var New Person (); // Use Object P.sayhello ();

This constructor and the method of creating the object are simple, and we can see that this in the constructor refers to the newly created object or the reference to the newly created object.

Let's examine how this code creates a new object. The program prefers to define a person function

1. When the program executes to this sentence, the function body is not executed, so the JavaScript interpreter does not know the contents of the function

2. Next execute the New keyword, create the object, the interpreter opens up memory, gets a reference to the object, and gives the new object a reference to the function

3. Immediately after executing the function, the passed object reference is given to this. That is, in the construction method, this is the object that was just created by new

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

5. End of function, return this, give this to the left variable p

After analyzing the execution of the constructor, you can get that this in the constructor is the current new object.

Having just analyzed the point of this in the constructor, there is another problem in the constructor that is the meaning of return. The meaning of return in the constructor changes, first, If in the constructor, if an object is returned , the original intent is preserved . If the return is not an object, but rather such as a number, Boolean and string,null, undefined, then directly ignored, or return this. For example:

var function () {        this. Name = ' Tom ';          return {            name:' Jack '        };    };     var New fn ();     // The result is Jack .

Thus, execute var p = new fn (); After this code, p is the object after return. See Example 2 again:

var function () {        this. Name = ' Tom ';          return ' Jack ';    };     var New fn ();     // P is the object {name: ' Tom '}    // The result is Tom .

As you can see, the return statement is invalid because the return is followed by a string, and the function returns this. So I created a new object with the name attribute added.

There is also a fourth invocation pattern, context invocation pattern, due to the length of the relationship, I will be detailed in the next blog.

Four invocation patterns of functions in JavaScript

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.