javascript introductory tutorial (b): Variable

Hello everyone, I am starting today will be officially speaking grammar of javascript.
variable

js中的变量一般使用var来声明(es6的let不在本教程讨论范围内),可以用来定义任何种类的变量,如果只对变量进行了定义而没有赋值,这样变量会默认为undefined。

var a=100; 
var b="hello,world";
var c=true;


Variable lift

在js中,用var定义的变量会出现提升的效果,变量一般会提升到所在作用域的最顶部,简单来说就是,如果变量在函数中,就会提升到函数最顶部,如果在全局作用域(window)中,就会提升到所有代码的最顶部。
这里给一个例子:
 console.log(a);
 var a=100;
//输出结果为undefined

The code is actually true here:

var a;
console.log(a);
a=100;

Because a lift to the top is not assigned, the final output will be undefined, but under strict pro-test mode variable lift will not be affected.
(Upgrade: a variable declared more than once in the js, only the last statement valid)

No block-level scope

Any statements set braces pair belongs to a block, all variables in this being defined outside the block of code is not visible, we called block-level scope
in languages such as java and c, block-level the scopes is obvious, such as the following code:

#include <stdio.h> 
void main() 
{ 
int i=2; 
i--; 
if(i) 
{ 
int j=3; 
} 
printf("%d/n",j); 
} 

Running this code error. You can see, C language has a block-level scope, because j is defined in the statement block if, therefore, it is not accessible outside the block.

But in the js it is not true:

for(var i=0;i<3;i++){}
console.log(i); //输出3

So js, ​​there are no block-level scope, it only function scope variables inside a function can not be defined with var external access to, because after the end of the function call, variables are automatically destroyed.

(Hint: do not var variables within the function directly declared will default to global variables, such as: test = 100; this test outside the function still be accessed because the default global variables, but such a statement in strict mode variable be wrong)

So how block-level scope of it?
There is one kind of function in the js executed immediately, in which the variables defined generally will not leak to the outside world, since there has not been talk function, so I only mention a little later again, to speak.

I just focus on each part of the js clarify what specific thing we need to see for yourself, such as keywords, comments, case-sensitive, and so on, this tutorial is only suitable for the fragmented time to see if we can be harvest, I will be satisfied friends.

This article is reproduced in: ape → 2048 https://www.mk2048.com/blog/blog.php?id=hhchj11kjhj

Guess you like

Origin www.cnblogs.com/10manongit/p/12610225.html