Various invocation patterns of JavaScript functions

Source: Internet
Author: User

function is the first citizen in the JavaScript world, in other words, if we can master the use of JavaScript functions, then the use of JavaScript can be more adept. Anyone familiar with JavaScript should know that the same function, which is called in a different way, is the one that is most affected. Let's talk about the various invocation patterns of JavaScript functions.

The invocation pattern of a common function

The call pattern of the so-called normal function is also the simplest invocation pattern of JavaScript function, which is directly followed by a () implementation call, see the following code:

function func () {    Console.log (this = =  window);  True}func ();

In the code above, we declare a Func function with the function keyword, and we print This===window in the body, and then we call the function func directly, we can see that the console is directly printing out true, that is, the normal invocation pattern of the function, The this in the function body points to the Global Environment window . Students who do not know this can encounter a bug like this:

 var  color = ' GG ' ;  var  obj = {color:  ' red ' 

We declare a variable color and an object obj in the global context, and in object obj We also declare a color attribute of ' red ', a show method. And in the Show method, we also declare a function func1 and call the function of FUNC1,FUNC1 to print This.color.   Finally we run the Code obj.show (); Call the Show method inside obj. Students who do not know the characteristics of the normal invocation pattern of a function may think that the "red" will be promised at the console at this time. In fact at this time in the console promised that it should be GG. Because the invocation pattern of the function func1 is the normal function invocation pattern (even if it is called in the Show method of obj), the this in the function body is pointing to the Global environment window, so it prints the variable color under the global environment.

Some students may ask: if we want the FUNC1 function to print out the ' red ', how should we change? It's very simple, because Obj.color is the ' red ', so we just need to introduce the this to obj into the function func1:

var color = ' GG '; var obj = {    ' red ',    function() {        varthis ;         function func1 () {            console.log (that.color);  Red        }        func1 ();}    } Obj.show ();

In the above code, because the this in show is pointing to obj, we declare a variable in show that = this, which is used to introduce the this to the func1, and then the FUNC1 The This.color in the function body changes to That.color, at which point we want the ' red ' to print out on the console.

There may be a reunion now asking: Why is this in show pointing to obj? That's what we're talking about. The second invocation pattern of the JavaScript function: Method invocation pattern

Second, method invocation mode

The method invocation pattern is simply to invoke a JavaScript function as a method of an object, and when a function is saved as a property of an object, we call it a method, such as show in the Obj object above, when a method is called, the inside of the function body is bound to this object , such as this in the show above. The method invocation pattern is also easily distinguishable: Obj.show (), object name. property name (); The code can refer to the OBJ code above, the blogger will not write more. Remember that the invocation of a method can access the object to which it belongs by using this in the body of the function.

Third, constructor invocation pattern

  The blogger thinks that the constructor invocation pattern is a more complex call pattern relative to other modes. The keyword new allows you to invoke a function as a constructor. The keyword new can change the function's return value:

functionFunc2 (name) { This. Name =name;}   Name //undefined//normal function call patternvarFoo = Func2 (' Afei '); foo; //undefinedName//Afei//constructor Invocation PatternvarBar =NewFunc2 (' Lizefei ');
bar.__proto__ = = = Func2.prototype; Truebar; //{name: ' Lizefei '}Bar.name;//' Lizefei '

In the code above we declare a function FUNC2, which is called with two different invocation patterns. Because the function Func2 does not return a value explicitly, it does not return anything as a normal function, so the value of foo is undefined.  Because the this of the normal invocation pattern is pointing to the Global Environment window, so Func2 (' Afei '); , the global environment has one more name variable and equals ' Afei '.

When FUNC2 is called as a constructor, we can see that it returns an object because the keyword new causes the function to have a special change in the invocation as follows:

    1. A new object is created, and this new object is linked to the prototype property of the Func2.
    2. This point in the function points to the new object.
    3. If there is no explicit return value, the new object is returned as the return value of the constructor Func2 (so bar is {name: ' Lizefei '})

  so we can see what the constructor does: Initialize the newly created object with the function's call. in JavaScript's object-oriented programming, this is quite important.

Because in the declaration of a function, there is no difference between a function that is called as a constructor in the future and the declaration of a normal function, so it is easy for later developers to fail the program because of errors in calling patterns. So the developers all agree that the first character of the function name used to make the constructor call should be capitalized , for example: Person,people. This way, the next developer will know that the function is called using the constructor call pattern as soon as they see the function name.

Iv. using the Apply () and call () method calls

This mode of invocation is created for more flexibility in controlling the context in which the function runs. The simple thing is to control the value of this in the function body flexibly.

The first parameter of both the apply and call methods is to pass the object that is being used by the function context (the simple point is that the object to bind to the function this). The other parameters are different:

The second parameter of the Apply method is an array, and the value inside the array is used as the parameter of the function call;

Call method, from the second parameter (including the second parameter), the remaining parameters are as parameters of function calls;

Let's look at chestnuts:

var obj = {    name:' Afei '}function  say (ag1,ag2) {    Console.log (ag1  this. name);} Say.apply (obj,[//Apply method: Hello Afei//callmethod: Hi Afei

As the chestnut shows, we call the function say as the context of the function say, so this in the function is pointing to the object obj. In the Apply method, we pass two parameters (' Apply method ' and ' Hello ') to the Say method through the array [' Apply method ', ' hello '], so print it out: The Apply method: Hello Afei.

The same call is the same, and the way the function is passed through the above code also at a glance at me, bloggers do not explain more.

In addition, bloggers also heard that the two methods of apply and call, in addition to the way the parameters are passed, the speed of execution or apply than call to be faster. However, the blogger has not experimented.

V. Summary

In JavaScript, the function as long as the invocation pattern is this kind of (in ES6 there is a very strange and special function call pattern, called ' tag template ', where Bo Master also said, there is no more), as long as the master of the main mode of invocation, then no need to worry about this The value of the change to change.

If there is a leak, the wrong place, I hope that the small partners pointed out that younger brother to learn modestly.

PS: Reprint please indicate the source http://www.cnblogs.com/afeihome/

Various invocation patterns of JavaScript functions

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.