日期:2014-05-16  浏览次数:20390 次

JS base knowledge (2) - 变量
关于变量类型和hoisting

变量类型:
(一)根据变量的作用域分:
局部变量:作用域在函数体内,
全局变量:定义在函数体外。

(二)根据存储方式分:基本类型和引用类型
和JAVA一样,基本类型放在栈中(因为长度固定),引用类型在堆中。
基本类型:
number, boolean, string
引用类型:
var refChar = new String("hello");//内置构造函数
var pair = {id:1, age:28};//自定义

参数传值方式:
和JAVA一样,pass-by-value.
基本类型,拷贝其值传入函数。引用类型拷贝地址值传入。

Hoisting
Function declarations and variable declarations are always moved ("hoisted") invisibly to the top of their containing scope by the JavaScript interpreter.
javascript 编译器会将函数声明和变量声明提升至当前作用域的开始。

function test(){
console.log(i);// undefined
//console.log(j); // ReferenceError: j is not defined
var i="a string";
console.log(i);// "a string"
fun1();// "this is fun1"
fun2();// ReferenceError: fun2 is not defined
function fun1(){
console.log("this is fun1");
}
}
test();


注意:函数赋值不会被hoisted...
function test() {
	bar(); // "bar will run!"
	foo(); // TypeError "foo is not a function"
	function bar() { // function declaration, given the name 'bar'
		console.log("bar will run!");
	}
	var foo = function () { // function expression assigned to local variable 'foo'
		console.log("this won't run!");
	}
}
test();


结论:
总是用var来修饰局部变量。
推荐把所有的局部变量声明在函数的开始。(就不会有hosting-related的困惑)

参考:
http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting