Introduction to JavaScript functions and scopes

Source: Internet
Author: User

Introduction to JavaScript functions and scopes

Yun Zhengjie

Copyright Notice: Original works, declined reprint! Otherwise, the legal liability will be investigated.

I. basic Functions

For a function parameter in JavaScript, the number of actual arguments may be less than the number of formal parameters, and all actual parameters are encapsulated in the special value arguments within the function. The functions in JavaScript are basically divided into the following three categories:

1<! DOCTYPE html>234<meta charset= "UTF-8" >5<title> basic functions of Yun Zhengjie </title>67<body>8 9<script>Ten     //1. General function Definition One     functionGet (name) { AConsole.log (name);//Print Variables -     } -Get ("Yinzhengjie"); the  -     //2. Auto Execute function, -(function(age) { -alert (age);//the variable of the popup effect +}) ("18"); -  +     functionfunc (Arg) { A Arg () at     } -     //3. Anonymous functions, which can be passed as a parameter.  -     varYZJ =function() {alert ("Yun Zhengjie"))}; - func (YZJ) -  -</script> in  -</body> to

Two. Scope

1. What is a scope

  Each function in JavaScript has its own scope, and when a function is nested, a scope chain appears. When the inner-layer function uses a variable, it is based on the scope chain from the inner to the outer layer of the loop, and if it does not exist, the exception. The scope of a variable is determined at the time of the declaration rather than when the execution is invoked. That is, all scopes already exist when the function is created and not executed.

1<! DOCTYPE html>234<meta charset= "UTF-8" >5<title>Title</title>67<body>8<script type= "Text/javascript" >//If you do not write the type, the default is Type= "Text/javascript", the annotation method and Golang similar. 9 vara=100,b=200; TenWINDOW.A =100; OneWINDOW.B = 200; A functionA () { -     vara=33,b=99; -     functionB () { the         varA=11,b=22; -Console.log (A +b); -     } -     returnB () + } - A () +</script> A</body> at

2. Lexical analysis

  What if our browser is parsing our HTML file? In fact, the browser built-in Html,css,javascript engine separately parse different code. The JS engine of the browser, when it encounters a function, performs a pre-compilation before the function executes, and this pre-compilation process is lexical analysis. Will form an active object, namely, "active", or "AO". Lexical analysis is broadly divided into the following three steps:

A>. Parameters of the parse function:

If there are no parameters, the AO object does not have any properties, for example: Ao.age = undefined. If there is one, accept the value of the parameter. such as Ao.age = 100.

B> The variable declaration of the parse function:

Will get all the variable names within the function once, we say that if there is no function life expression is not processed, the variable name is the active object, it will save all the variables, and assign a value of undefined, when the function is called, it will be assigned operation.

C>. function declaration expressions for analytic functions

The so-called function declaration expression is the keyword "function () {}", if there is a duplicate function name and variable name, the variable name will be used to overwrite the previous variables yo!

1<! DOCTYPE html>234<meta charset= "UTF-8" >5<title>Title</title>67<body>8<script>9     varstr = "locale";//of course, you can also write: Window.str = "locale";Ten  One     functionT () { AConsole.log (str);//output "undefined" -         varstr = "Locale"; -Console.log (str);//output "locale" the     } - t (); -</script> -</body> +Scope Case 1
1<! DOCTYPE html>234<meta charset= "UTF-8" >5<title>Title</title>67<body>8<script>9     functionT (age) {TenConsole.log (age);//at this point, age has been overridden by the following function expression, so its value is: "Function age () {}", One         varAge =99; AConsole.log (age);//its value should be 99 because we have defined his value on his previous line.  -         functionAge () { -         } theConsole.log (age);//in the same vein, the value is still -     } -T (5); -</script> +</body> -Scope Case 2

If your knowledge of the analysis of the word law and very thorough, then the above 2 enterprises of the face test, you can see the true true?

Three. closure function

1. What is a closure function

The official explanation is that closures are an expression (usually a function) that has many variables and environments that bind them, and so these variables are also part of the expression. It is believed that very few people can read this sentence directly because he describes it as too academic. My understanding of the closure function is that the function that the parent function can take to the variable of the child function is called the closure function. Believe in learning the scope, also understand the meaning of global variables and local variables, we can know that in the function, a local variable scope can easily get the values of global variables, but in the scope of global variables to get the local scope of the variable will have to use the closure function.

2. The role of closures

Closures can be used in many places. Its maximum usefulness is two, one of the previously mentioned variables that can read the inside of a function, and the other is to keep the values of these variables in memory at all times. We can look at the following cases:

1<! DOCTYPE html>234<meta charset= "UTF-8" >5<title> Yun Zhengjie's closure function </title>67<body>8<script>9     functionA () {Ten         varn= 999; OneNadd =function() {n+=1001}; A      functionB () { - alert (n); - } the       returnB; - } -     varresult=A (); -Result ();//called the A function, the two variables of N and Nadd are generated, while the execution results of B are returned. +Nadd ();//We will execute the anonymous function Nadd.  -Result ();//since the Nadd anonymous function is executed above, that is, the value of n is increased by 1001, we should see that the result should be 2000.  +</script> A</body> at

3. note points for using closures

A> Because the closure will make the variables in the function in memory, memory consumption is very large, so can not abuse closures, otherwise it will cause the performance of the Web page, in IE may lead to memory leaks. The workaround is to remove all unused local variables before exiting the function.

B> The closure will change the value of the inner variable of the parent function outside the parent function. So, if you use the parent function as an object, take the closure as its common method, and take the internal variable as its private property (private value), then be careful not to casually Change the value of the inner variable of the parent function.

Four. Object-oriented

In fact, in JavaScript programming, there is no object class defined with a keyword, unlike Python or other languages such as Golang, which has the keyword "class" or "type ... struct" to declare an object. When we define a JavaScript object, we actually use the Function keyword to define it, but when we define the function and ask if the first letter is capitalized, the unspoken rule is to capitalize the first letter of the function name when defining an object.

1<! DOCTYPE html>234<meta charset= "UTF-8" >5<title> Yun Zhengjie Object-oriented </title>67<body>8<script>9     //define a JavaScript class and initialize the internal data. Ten     functionFoo (name,age) { One          This. Name =name; A          This. Age =Age ; -     } -  the     //give us a definition of J-specific methods. We call this the use of prototype implementation method reuse. -Foo.prototype = { -"Show":function () { -Alert This. Name); +         }, -"Print":function () { +Alert ("Yun Zhengjie"); A         } at     }; -  -     //instantiate the object we defined, generating obj. -obj =NewFoo ("Yun Zhengjie", 18); - alert (obj. Name); - alert (obj.print); in  -</script> to</body> +

Introduction to JavaScript functions and scopes

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.