Javascript variable scope Summary

Source: Internet
Author: User
Document directory
  • Question 1
  •  
  • Question 2
  • Question 3
  • Question 4
  •  
  • Question 5
  • Question 6
  • Question 7
  • Question 8
  • Question 9
  • Question 10
  •  

In JavaScript, variable scope is a problem that often leads to headaches. The following is a summary of the frequent and error-prone situations through more than 10 questions, the sample code is very short and easy to use.

Question 1
VaR name = 'casper '; alert (name); // output without a doubt: Casper
Question 2
Alert (name); // error: the object is undefined, that is, a non-existent variable is used, so the error age = 24; // here is an error, but is age defined? Flip down the rhino book and understand // assign a value to an undefined variable. A global variable is created, which is equivalent to: var age = 24.
Question 3
Alert (name); // It is defined under name. Is an error reported here? Error! Undefinedvar name = 'casper ';
Explanation: when parsing JavaScript code, it will search for the variables declared by VAR and declare them in advance. The actual process is as follows:
VaR name; // declare the name variable without assigning a value. Therefore, the variable is undefinedalert (name); name = 'casper ';

 

Question 4
VaR name = 'casper '; function show () {alert (name); name = 'hello'; // change the value of the global variable name to 'Hello'} Show (); // output: Casper
Question 5
VaR name = 'casper '; function show () {alert (name); // output: undefined, is there a desire var name = 'Hello'? // note: compared with question 4, there is a var before name,} Show ();

Explanation: In function show, name is a local variable. The principle of Question 3 also applies to this, that is, the function show is actually

(Note: When a function has a local variable with the same name as an external global variable, the local variable is used first, and the name is used here)

function show(){    var name;    alert(name);    name = 'hello';}

 

Question 6
VaR list = [1, 2, 3]; function show () {If (typeof list = 'undefined') {list = [];} alert (list. length) ;}; show (); // result: 3. Whether it is clear at a glance =. Wait a moment. Check the seventh question.

 

Question 7
VaR list = [1, 2, 3]; function show () {If (typeof list = 'undefined') {var list = []; // note that, compared with question 6, there is a var} alert (list. length) ;}; show (); // result: 0. Do you want to die suddenly?

Explanation: javascript has no block-level scope (that is, the scope defined by {}). All variables declared in the function are defined no matter where they are declared, this is often different from C ++ and so on.

So let's take a look at the actual internal parsing logic of the show method.

Function show () {var list; // list is a local variable. If (typeof list = 'undefined') {list = [];} is not assigned here. alert (list. length );};

 

Question 8
Alert (typeof show); // result: function. Please trust your eyes. You have not read the function show (){}

Explanation: The process of JavaScript code parsing is similar to a function declared in the form of function show (). Like the variables declared by VAR, it will be mentioned at the beginning. The difference is that, function declaration and definition are completed at the same time, but the value assignment of the variable declared by VAR will be completed later.

 

Question 9
Alert (typeof show); // result: Undefined. please polish your eyes again. You did not see var show = function (){};

Explanation: UseFunction DefinitionAndFunction expressionDefine functions. There are some differences between the two processes.

Function Syntax: function show (){}

Function expression: var show = function (){}

When the function definition declaration method is used, the function definition is advanced. When the function expression declaration method is used, the function definition is the same as the local variable declared by var, but the function definition position remains unchanged. The process is as follows:

var show;alert(typeof show);show = function(){};

 

Question 10
var data = {name:'casper'};function data(){    alert('casper');}data();  //TypeError: object is not a function

Is there an impulse to smash the display... Data is actually {Name: 'casper '}, and an object is called as a function, so an error is reported.

As mentioned above, variables declared by function declaration (defined by function) and VAR will be advanced, but there will be orders as follows:

function data(){    alert('casper');}var data;data = {name:'casper'};data();

Slightly modified, the results are different:

VaR DATA = {Name: 'casper '}; var DATA = function () {// declare the function alert ('casper') through a function expression;} data (); // result: Casper

The process of combining the above is as follows:

VaR data; data = {Name: 'casper '}; Data = function () {alert ('casper');} data (); // result: Casper

 

Summary: The javascript scope problem is really a headache. as the basis, it is necessary to clarify it. The above lists many error-prone scenarios, however, the actual situation may be more complex than this. The closure, this, the scripts between different segments (that is, the scripts are scattered in the multi-segment <SCRIPT> tag) and so on won't be expanded here. If any of the above content is incorrect or incorrect, please note.

 

Background: A brother asked a question about the variable scope last night. He gave the answer with confidence and then... Go back to the rhinoceros book and read it again. The following is just a memo. You can check whether you can see the correct answer in a few days...

 

 
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.