The beauty of JavaScript functions ~

Source: Internet
Author: User

the beauty of JavaScript functions ~

In this article, I will recognize the functions in JavaScript in the following ways.

    • Why is a function an object and how do I define a function ?
    • How to understand that a function can be passed as a value
    • Internal objects, methods, and properties of a function

Part I: Why is a function an object and how to define a function

  The most interesting thing about JavaScript is probably the function, because, unlike other languages, in JavaScript, each function is an instance of the type of functions, and we know:object is an underlying type, All other types inherit the basic behavior from Object . That is, function is also inherited from the object reference type, so it is not difficult to understand that as an instance of the functions type.

So how do you define a function? In general, there are three ways to define a function.

First: function declaration. This syntax, like other forms of language, is one of our most common ways. As follows:

function Add (num) {    return num+10;}

Second: the function expression. As follows:

var add=function (num) {    return num+10;};

We can notice that the definition function method of the function expression takes the function as an expression, so the final one is a semicolon, and after the function has no name, how do I call it? In fact, it can be referenced by Add. (In fact, the add here is a property or method of the global object, which is represented in the browser as a Window object)

Third: Use the function constructor. As follows:

var add=new Function ("num", "return num+10");

Function constructors can receive any number of arguments, the last of which is the function body, and the arguments of the previous functions. This method is not recommended because it causes parsing of two code (the first is parsing the regular ECMAScript code, the second is parsing the strings passed into the constructor), which affects performance. But this approach helps us understand that a function is an object, and a function name is a pointer.

  Since we do not recommend a third method to create a function, it is seldom used in practice. So what's the difference between the first two methods?

In fact, the difference is simply whether the method of the function declaration causes the code to go through the function declaration to elevate the read and add the function to the execution environment, so that the JavaScript engine puts them at the top of the source tree, before it starts executing. The function expression does not. This may not be easy to understand, see the following example:

A

function say () {Console.log ("I like Coding");} Say ();

At this point I like coding is output on the console.

B

var say=function () {Console.log ("I like Coding");} Say ();

Similarly, I like coding is also output at the console.

C

Say (); function say () {Console.log ("I like Coding");}

Here we will say () This call function statement on the top, the same console also output I like coding.

D

Say (); var say=function () {Console.log ("I like Coding");};

However, there was a mistake here. Let's catch the following error.

Try{say (); var say=function () {Console.log ("I like Coding");};} catch (Err) {Console.log ("error is:" +err);}

Console tip: Error: Typeerror:say is not a function. The code above generates an error during run time because the function is not in a function declaration, but rather in an initialized statement, so that the variable sum does not hold a reference to the function if it is not executed to that statement. With a function declaration, the JavaScript engine promotes the function declaration to the top, and the function name sum holds a reference to the functions.

  

For a deeper understanding of the function as an object, the function name is a pointer, and we can explain it in the following example:

  

       function Add (num) {return num+10;} Console.log (add);//20var Addcopy=add;  At this point we assign the add pointer to AddCopy, so addcopy also points to the same function object Console.log (addcopy);//20 sum=null;  A major function of NULL is to hold an empty object, when sum points to an empty object Console.log (sum);//uncaught typeerror:sum is not a function (...) sum is an empty object, So there will be a syntax error console.log (addcopy)  ,//20 and addcopy point to the function object, you can get the correct answer    

It is also not difficult to understand that a function is not overloaded because it is an object whose function name (pointer) can have multiple (pointing to the same object).

Part Two: How to understand that a function can be passed as a value.

In general, the arguments in the function are variables. And since the function name is a pointer, it is also a variable, so we can use the function as a value.

As follows:

function Onefunc (antherfunc,argum) {return Antherfunc (argum),} function Antherfunc (str) {return str+ "I am JS";} console. Log (Onefunc (Antherfunc, "Ha"))//ha I am JS

In addition, a function can also be returned as the result of another function. As follows:

function Createcomparisonfunction (propname) {return function (OBJECT1,OBJECT2) {//This is a comparison function, although a physical parameter, but does not need to pass arguments, Just to facilitate the following call Var value1=object1[propname]; var value2=object2[propname];//the advantage of using the square bracket operator here is that when an object array is defined, the object is created using the object literal method, so the property name can be quoted, and the property name will not affect the result even if it is not canonical. It should be noted that, at this point, the last call will need to be called using square brackets. if (value1<value2) {return-1;} else if (value1>value2) {return 1;} else{return 0;};//Note: Although there is no semicolon to run here, it is best to write it. } var data=[{name: "Zhuzhen", Age:21},{name: "Heting", age:18}];//here to sort by what kind of attribute Data.sort (Createcomparisonfunction (" Name ")); Console.log (data[0].name);//heting Data.sort (Createcomparisonfunction ("Age")); Console.log (data[0].age);//18
Part III: Properties and methods of functions

We can start by summarizing what properties and methods the function has and what objects the function has.

Inner object of the function: this, arguments (it also has a callee property and a length property)

Method of the function: inherited from Object with TOSTRING0 (), ValueOf (), tolocalestring (). The method added by the function itself has call () apply () bind ()

Properties of the function: Length prototype caller

  

Inner object of a function: arguments and this 1.arguments object

In JavaScript functions, the function does not mind how many arguments are passed over. The number of arguments that are eventually passed in is not necessarily the number of arguments that you want to accept at the time of declaration. This is because there is a class array objectin the function arguments, the function receives this "array", we can use this "array" to get passed to the function of each parameter. That it is a class array object, not an array object, because it is not an instance of a reference type array, but we can use square brackets to access each of these elements. The third part of the beginning I introduced to arguments has two attributes, one is length one is callee.

Where the length property returns the actual number of arguments received by the function. Like what:

         function number () {Console.log (arguments.length+ "" +arguments[0]);} Number (12,45);//2 number ("hah", "hei", "You");//3 hah number ();//0 undefined    

As can be seen from the above code, although we do not want to receive parameters when declaring a function, but to the actual call, we can pass any number of arguments.

And we also output the first parameter passed in after the length, because number () does not pass in the parameter, so its first item is undefined.

The callee Property is also a property of the function's internal object arguments, which is a pointer to the function that owns the arguments object. With this property we can rewrite the recursive function of the factorial. First, let's look at the most common recursive functions.

               function factorial (num) {if (num<=1) {return 1;} else{return num*factorial (num-1);}} Console.log (factorial (3));//6        

This recursive function is well understood. That is, when we use factorial (3) to make a call, then immediately into the factorial function execution environment, and then instantly create a local variable num (formal parameters, although not with Var, but it is indeed a local variable inside the function) and assign a value of 3, after the judgement returned Factorial (2), because we think the return is how much, this function eventually get how much. Next, due to factorial (2), it entered the factorial execution environment again, and eventually returned to 3*2*factorial (1). Because of the presence of factorial (1), the equivalent of calling a function again, Entering the function execution environment again eventually gets 3*2*1=6. This then jumps out of the local execution environment into the global execution environment and destroys the local variable num.

However, there is a problem here, because the function is the object, the function name is a pointer, if we assign the factorial pointer to another pointer such as Anotherfactorial, and let the factorial pointer to an empty object, So what happens when you call anotherfactorial? See the following code:

                function factorial (num) {if (num<=1) {return 1;} Else{return num*factorial (num-1);}} var Anotherfactorial=factorial;factorial=null;console.log (Anotherfactorial (3));//uncaught TypeError: Factorial is not a function (...)

 

This is useless because the internal factorial is still there, and it is tightly coupled to the function. However, as long as the use of arguments callee This property can be a good solution to the problem.

        function factorial (num) {if (num<=1) {return 1;} Else{return Num*arguments.callee (num-1);}} var Anotherfactorial=factorial;factorial=null;console.log (Anotherfactorial (3));//6
Finally, the arguments object can compensate for defects that cannot be overloaded by functions.
function Onefunc () {if (arguments.length==1) {console.log (arguments[0]+10);} else if (arguments.length==2) {Console.log (arguments[0]+arguments[1]);} Else{console.log ("Please input one or both numbers");}} Onefunc;//55onefunc (12,37);//49onefunc ();//please input one or both numbers

  

2.this objects

This object is commonly referred to as the context object, which is an internal object that is automatically generated when the function is run, and because it is a function, it can only be used in functions (this is present in the function). If this occurs at most outside of the function, there is no later.). We can be divided into four kinds of situations to explain. Understand: In general, this is in which environment is called, this is pointing to where.

  The first: purely function calls.

  At this point the most common usage of the function, which belongs to the global property call, is that this represents window. You can see the following examples:

                var color= "Red"; var color= "Pink"; var o={color: "Blue"};function Saycolor () {console.log (this.color);} Saycolor ();//Pink    

This is finally pink, because it is purely a function call and is called in the global context, and finally to the window. That is, we will get window.color, and this time get pink, because pink in the after, covered Red,color finally pink. Similarly, if pink is in front, Red will eventually get red rather than pink.

Question: This may point to the Saycolor function? This is because there is no color in the Saycolor, so search the window object up and down the scope chain.

Take a look at the following example:

var color= "Red"; var O={color: "Blue"};function Saycolor () {    var color= "Black";    Console.log (This.color);} Saycolor ();//red

At this point, the red is obtained, and the black in the function is not obtained, stating that this does point to the Window object, not the Saycolor function, which is not the result of searching upward along the scope chain.

What if we define the color in the Saycolor () function as a global variable? As follows:

                Color= "Red"; var O={color: "Blue"};color= "pink"; function Saycolor () {color= "black"; alert (This.color);} Saycolor ();//black    

Why not get pink here, but get the black in Saycolor? This means that once the Saycolor function is called, it enters the execution environment of the Saycolor () function, and the variables inside the function are created, since the color inside the function is not declared with Var, so the function knows that a global variable is created. So the function thought: Your heart is not my this why I want you, and then threw the global variable into the global environment, but there must be a first served bar, so Color= "Black" was thrown to color= "pink" behind. Or just follow first served's past, however, it will eventually overwrite the color defined above.

The second type: called as an object method.

    The function can also be used as a method call for an object ( this sentence needs to be carefully understood ), and this point points to the parent object. As in the following example:

                

of the O.saycolor=saycolor; This means that the function is used as the object's method. So this is pointing to this parent object o, and finally getting blue is not hard to understand. It is important to note that the name of the function is simply a variable that contains pointers, so that the global Saycolor () function and the O.saycolor () function still point to the same function, even if executed (referenced) in a different environment.

  The third type: as a constructor

The so-called constructor, which generates a new object through this function, points to the new object at this point. As shown in the following example:

                function Num (x) {this.x=x;}; var o=new Num (2); Console.log (o.x);//2  

We passed the Num constructor and initialized the object o, so this point points to this object o, which means that this.x is actually a o.x, and we passed 2 at initialization, which is actually o.x=2.

The fourth case: the Apply () method of the function, the call () method of the function, and the bind () method of the function.

These methods I will explain below.

Method of B function

Functions as an instance of a function reference type, it must inherit some of the object's methods, but in order to ensure its uniqueness, it must also have a non-inherited method.

First: Methods of inheritance

The methods that the function inherits from the object reference type are the valueof () method, the ToString () method, and the toLocaleString () method. They will eventually return the code of the function:

                function Add () {return 20;} Console.log (Add.tostring ()); Console.log (add.tolocalestring ()); Console.log (add.valueof ());

Not surprisingly, they eventually return to the function itself, namely:

                function Add () {return 20;}
Second: A non-inherited method.

Non-inherited methods include apply (), call (), and bind (), which is exactly the method I omitted when I spoke about the fourth case of this object, which I will explain here.

  both the Apply () method and the call () method are called functions in a specific scope, and are actually equivalent to setting the value of the This object in the function body . At the same time, both receive only two parameters, the first parameter is the scope of the run function, and the second parameter is slightly different , the second parameter of the Apply () method is to receive an array (an instance of array) or a arguments object, while call () The second parameter of the method is to enumerate all the arguments to be passed to the function. Examples are as follows:

function sum (num1,num2) {return num1+num2;} function Callsum (num1,num2) {return sum.call (this,num1,num2);//call () method must all be enumerated}function callSum1 (num1,num2) { Return sum.apply (this,arguments);//apply () method can pass a arguments object}function callSum2 (num1,num2) {return sum.apply (this, [num1,num2]); The/apply () method can also pass an array (an instance of array)}console.log (Callsum (10,10));//20console.log (CallSum1 (10,10));//20console.log ( CallSum2 (10,10));//20

The above example does not change the scope of this, and knowledge introduces the method of passing a second parameter. the real function of the apply () and call () methods is to extend the function to run the scope.

  

        Window.color= "Red"; var O={color: "Blue"};function Saycolor () {console.log (this.color);} Saycolor ();//redsaycolor.call (this);//redsaycolor.call (window);//redsaycolor.call (o);//blue

The first is to implicitly call the function in the global scope, and the second third is to explicitly call the function in the global scope, most of which is to call the function in the object o, so this points to O, and finally to the O.color. The summary is what the first parameter of call and apply is, where the function is called, i.e. where this is pointing.

    

  The last method is bind (), which can only receive one parameter, representing the scope of the calling function, that is, it has the same effect as the first two methods. It's just that it has to be assigned to a variable before the variable is called.

Window.color= "Red"; var O={color: "Blue"};function Saycolor () {console.log (this.color);} Saycolor ();//redvar s=saycolor.bind (o); s ();//blue

  

  C. Properties of a function

As we have said, functions generally have three properties: Length,caller,prototype

First: Length Property

This property is simple, called by a function, that returns the number of arguments the function expects to accept. As shown below:

function A (num1,num2) {return num1+num2;} Function B (num1,num2,num3) {return num1+num2+num3;} Console.log (a.length);//2console.log (b.length);//3

   Note: The length property of the function is the number of arguments that the function expects to accept, whereas the length property of the function's internal object arguments is the number of arguments that actually pass in the function, and the two are not the same. 

Second: Caller property

This property returns the function that called the current function. As shown below:

function A () {B ();} Function B () {Console.log (B.caller);} A ();

After calling a (), we can see in the console:

        function A () {B ();}

  NOTE: Caller returns the function that called the current function, and callee returns the function that the arguments object is subordinate to.

Third: Prototype property

This property is very important and few words cannot express it completely, I will describe it separately in the blog post later.

Click here to return to the beginning of the blog

The beauty of JavaScript functions ~

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.