[译]Javascript中的本地以及全局变量

本文翻译youtube上的up主kudvenkat的javascript tutorial播放单

源地址在此:

https://www.youtube.com/watch?v=PMsVM7rjupU&list=PL6n9fhu94yhUA99nOsJkKXBqokT3MBK0b

Javascript中有两种变量

1.本地变量

2.全局变量

Javascript本地变量:本地变量是在函数里边被申明的.这些变量的作用域在本地,这就是说这些变量仅仅在包含其的函数内部可用.本地变量在函数启动时被制造,然后在函数运行结束后立马被删除.

function helloWorld() 
{
    var greeting = "Hello";
    // The variable greeting is available in the function
    greeting = greeting + " JavaScript";
    alert(greeting);
}

helloWorld();

// The variable greeting is not available outside the function
// Error : 'greeting' is undefined
alert(greeting);

Javascript全局变量:全局变量就是在函数外被声明的变量.全局变量的作用域为全局,这也就是说,所有的在页面上的脚本和函数都可以获取这些变量.全局变量在其被声明后则诞生,而当页面被关闭时才会消亡.

// Global variable
var greeting = "Hello";

function helloWorld() 
{
    // The variable greeting is available in the function
    greeting = greeting + " JavaScript";
    alert(greeting);
}

helloWorld();

如果你给一个没有被声明的变量赋值的话,那么它就会自动成为一个全局变量,甚至当其在函数内部被呈现也是如此.

function helloWorld() 
{
    // The variable greeting is not declared but a value is assigned. 
    // So it will automatically become a global variable
    greeting = "Hello JavaScript";
}

helloWorld();

// Variable greeting is available outside the function
alert(greeting);

本地变量可以和全局变量有一样的名字.改变一个变量的值并不会对另外一个有影响.如果变量值在函数内部被修改,则其本地变量版本的变量值会被改变.如果变量在函数外被修改的话,则其全局变量版本的变量值会被改变.

var greeting = "This is from global Variable";

function helloWorld() 
{
    var greeting = "This is from local variable";
    document.write(greeting + "[br/]");
}

// This line will modify the global greeting variable
greeting += "!!!";

helloWorld();

document.write(greeting);

Output : This is from local variable This is from global Variable!!!

有的时候,本地和全局变量拥有相同的名字,在变量上升(hositing)的影响下,会出现无法预期的行为

var greeting = "This is from global Variable";
helloWorld();

function helloWorld() 
{
    document.write(greeting);
    var greeting = "Hello from local variable"
}

Output : undefined

由于变量上升(hoisting)的存在,以上的程序其实本质上如下:

var greeting = "This is from global Variable";
helloWorld();

function helloWorld() 
{
    var greeting;
    document.write(greeting);
    greeting = "Hello from local variable"
}

{}是不会在Javascript中制造作用域的:在以下的例子中,otherNumber是一个在{}内定义的全局变量.在很多其他语言,比如C#或者Java,{}是会制造作用域的,但是Javascript则不然

var number = 100;

if (number ] 10) 
{
    var otherNumber = number;
}

document.write(otherNumber);

Output : 100

 

 

原文地址:https://www.cnblogs.com/otakuhan/p/7771088.html