Various common function definition methods in JavaScript _ javascript skills

Source: Internet
Author: User
This article mainly introduces various common function definition methods in JavaScript, including some techniques for testing and analysis, for more information, see the following section to describe various common function definition methods in JavaScript. The specific analysis is as follows:

First, let's take a look at the four most common function definitions in JavaScript:

Use Function to construct a Function defined by a Function. The Code is as follows:

var multiply = new Function('x', 'y', 'return x * y;');

Function declaration. This method is also the most common one:

function multiply(x, y) {  return x * y;}

Function expression, declared as an anonymous function, and assigned a variable. A common method is as follows:

var multiply = function(x, y) {  return x * y;}

Function expression, but the function declaration is the name function and then assigned to a variable. It looks like the previous method:

var multiply = function multi(x, y) {  return x * y;}

First, compare the function name and the direct relationship between the function variables assigned by the function, such as the true circle ...... Intuitively, from example 4, the relationship between the multiply function variable and the multi function name is as follows:

Function names cannot be modified. On the contrary, function variables can be assigned again. It should be easy to understand that function variables can be re-assigned. In our 4th example, the defined multiply variable is not pleasing to the eye, and the re-assigned value is:

multiply = function(x, y) {  return x + y;}

Immediately changed from multiplication to addition. However, changing the multi function variable is impossible. The function definition is already there. As long as the reference is retained, it will not change. It may not be easy to understand here, let's think about it first. Let's look at it and we should be able to understand it.

Function names cannot be used outside the function. They are only visible within the function body. A simple example is as follows:

Var foo = function bar () {alert ('hello');} foo (); // The prompt "hello" string bar (); // The execution reports an error. The bar is undefined.

And obviously, the bar here is indeed a function name, but it cannot be called externally. At this time, there will certainly be children's shoes to ask why this example is still so cool, just like Example 4. Why not use case 2? I have a good question, and I think it's time to break it down.

In Example 4, we can see that the function name (multi) and function variable (multiply) are different. In fact, there is no relationship between the two, so there is no need to maintain consistency. Speaking of this, I think the above four examples can be reduced to three, and the essence of Example 2 and Example 4 should be consistent. What, believe it? Hey, I have to continue selling the customs ~ Continue reading ~~

We found that compared with example 4, Example 2 only lacks the var function variable. Compared with example 4, Example 3 only lacks the function name. From the symptom, the essence of Example 2 and Example 4 is the same. The evidence is as follows:

Function foo () {} alert (foo); // The system prompts the name of the function containing "foo" var bar = foo; alert (bar ); // The prompt still contains only the function name "foo", which has no relationship with bar half dime

It is indeed an iron certificate, right? Is the above Code similar to Example 2 combined to write in Example 4? Correct. This is what I just mentioned. The two should be essentially the same, but when we define a function in Case 2, The JS engine helped us do something, for example, declaring a function named multiply, at the same time, we also quietly defined a variable also called multiply, and then assigned this variable with two identical names. We thought we were using the function name multiply, actually, I'm using the multiply function variable. I'm dizzy ~ To be honest, I am also dizzy ~~ In short, when we call the function, we actually call the function with function variables, and the function name cannot call the function externally. Therefore, I have inferred the above.

But here is a small difference. The function defined in the function declaration method is different from the declaration of the constructor or function expression, function declaration functions can be called before function definition ...... If you don't talk about it, check the Code:

Foo (); // prompt Foofunction foo () {alert ('foo');} bar (); // dude, it is really different from above, so don't renew it, isn't this an error? Prompt bar. var bar = function () {alert ('bar');} is not defined ');}

Let's talk about the Function declared by the constructor. In this way, the declared function does not inherit the scope of the current declared position. By default, it only has the global scope, however, this is the same for several other function declaration methods, as shown below:

Function foo () {var hi = 'hello'; // return function () {// alert (hi); //}; return Function ('Return hi; ');} foo (); // you can view the execution result by yourself.

It is conceivable that an error is inevitable for the execution of the function returned by using the constructor declaration, because its scope (that is, the global scope) does not contain the hi variable.

Another point is that it is often said that the efficiency of the function declared in the constructor method is low. Why? Today, I learned from the document that the functions declared in the other three methods will only be parsed once. They actually exist in the closure, but they are only related to the scope chain, the function body is parsed only once. However, in the constructor mode, the function body is parsed every time a function is executed. We can think that the declared function is an object, which stores parameters and function bodies, the parameter and function body must be parsed before execution. This will inevitably lead to inefficiency. I don't know how to do this experiment?

Finally, we don't know much about it. When does it look like the function declaration method is not the Function life method ~ To put it simply, the method of Example 2 will become a different method when it is inadvertently ):

When it becomes a part of the expression, it is like Example 3 and Example 4.
It is no longer the source element of the script or function ). What is a source element? That is, A non-nested statement or function body (a "source element" is a non-nested statement in the script or A function body) in the script. For example:

Var x = 0; // source element if (x = 0) {// source element x = 10; // not a source element, because function boo () {}/not a source element is nested in the if statement, it is nested in the if statement} function foo () {// source element var y = 20; // source element function bar () {}// source element while (y = 10) {// source element function blah () {} // not a source element, because it is nested in the while statement y ++; // not a source element, because it is nested in the while statement }}

The concept of the source element is probably understood. For more information about the function declaration just mentioned, see:

// Function declaration function foo () {}// function expression (function bar () {}) // function expression x = function hello () {}if (x) {// function expression function world () {}} // function statement function a () {// function statement function B () {} if (0) {// function expression function c (){}}}

At last, let's talk about my own understanding. The reason why we need to distinguish between function declaration and non-function declaration is that I have read the function definition in the function declaration method, when the JS parsing engine is executed, it will be declared in advance, that is, as we mentioned above, it can be used before function definition, in fact, the parsing engine has resolved it before we use it, but the non-function declaration is like expression function declaration. The JS parsing engine only defines the variables declared by var in advance, at this time, the variable value is undefined, and the true value assigned to this variable is in the actual location of the Code. Therefore, the above mentioned errors are all undefined. The actual variable has been defined, but no value has been assigned, the JS parsing engine does not know it as a function.

I believe this article provides some reference value for javascript WEB programming.

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.