標籤:變數提升 htm oca ram execution 問題 foo 執行 att
參考了這篇文章
http://www.jb51.net/article/30719.htm
var v=‘Hello World‘;(function(){ console.log(v);})()輸出:Hello World
但是
var v=‘Hello World‘;(function(){ console.log(v); var v = ‘hi‘;})()輸出:undefined
這裡面隱藏了一個陷阱-----JavaScript中的變數提升(Hoisting).在JS中,就是把定義在後面的東東(變數或函數)提升到前面中定義。
首先看變數範圍(scoping),與C++不一樣:
var x = 1;console.log(x); // 1if (true) { var x = 2; console.log(x); //2}console.log(x);// 2
這是因為:
塊,就像if語句,並不會建立一個新的範圍。只有函數才會建立新的範圍。
如果你必須在函數中建立一個臨時的範圍,請像下面這樣做:
function foo() { var x = 1; if (x) { (function () { var x = 2; // some other code }()); } // x is still 1. }
變數提升,很簡單,就是把變數提升提到函數的top的地方。我麼需要說明的是,變數提升 只是提升變數的聲明,並不會把賦值也提升上來。
比如我們定義三個變數:
(function(){ var a=‘One‘; var b=‘Two‘; var c=‘Three‘; })()
實際上它是這樣子的:
(function(){ var a,b,c; a=‘One‘; b=‘Two‘; c=‘Three‘; })()
這個時候就把變數提升了呀。
函數提升:
是把整個函數都提到前面去。
在我們寫js code 的時候,我們有2中寫法,一種是函數運算式,另外一種是函式宣告方式。我們需要重點注意的是,只有函式宣告形式才能被提升。
函式宣告方式提升【成功】 代碼如下:function myTest(){ foo(); function foo(){ console.log("我來自 foo"); } } myTest(); 結果:我來自 foo
另一種函數運算式,就不行:
函數運算式方式提升【失敗】 代碼如下:function myTest(){ foo(); var foo =function foo(){ console.log("我來自 foo"); } } myTest(); 結果:foo(); ^TypeError: foo is not a function
另外,下面文章裡面還有幾個例子
http://www.jb51.net/article/30718.htm
例子一:
var foo = 1;function bar() { if (!foo) { var foo = 10; } console.log(foo);}bar();結果:10
但是
var a = 1;function b() { a = 10; return; function a() {}}b();console.log(a);結果:1
另外注意,把function a注釋掉:
/** * Created by baidu on 16/10/24. */var a = 1;function b() { a = 10; return; //function a() {}}b();console.log(a);
輸出:
10
原來,function b裡面的a沒有加var,表示用的是全域變數。如果加上var,那結果會不一樣:
var a = 1;function b() { var a = 10; return; //function a() {}}b();console.log(a);結果:1
再回到上面第2段代碼,其實是因為函數提升,把function a 提到了前面
var a = 1;function b() { a = 10; return; function a() {}}b();console.log(a);結果:1
在JavaScript中,一個範圍(scope)中的名稱(name)有以下四種:
1. 語言自身定義(Language-defined): 所有的範圍預設都會包含this和arguments。
2. 函數形參(Formal parameters): 函數有名字的形參會進入到函數體的範圍中。
3. 函式宣告(Function decalrations): 通過function foo() {}的形式。
4. 變數聲明(Variable declarations): 通過var foo;的形式。
函式宣告和變數聲明總是被JavaScript解譯器隱式地提升(hoist)到包含他們的範圍的最頂端。很明顯的,語言自身定義和函數形參已經處於範圍頂端。這就像下面的代碼:
function foo() { bar(); var x = 1; }
實際上被解釋成這樣:
function foo() { var x; bar(); x = 1; }
注意到聲明的賦值部分並沒有被提升(hoist)。只有聲明的名稱被提升了。
這和函式宣告不同,函式宣告中,整個函數體也都會被提升。
但是請記住,聲明一個函數一般來說有兩種方式。
function test() { foo(); // TypeError "foo is not a function" bar(); // "this will run!" var foo = function () { // 函數運算式被賦值給變數‘foo‘ alert("this won‘t run!"); } function bar() { // 名為‘bar‘的函式宣告 alert("this will run!"); } } test();
在這裡,只有函式宣告的方式會連函數體一起提升,而函數運算式中只會提升名稱,函數體只有在執行到指派陳述式時才會被賦值。
Name Resolution Order
需要記住的最最重要的特例就是名稱解析順序(name resolution order)。
上面列出的就是解析的順序:
1. 語言自身定義(Language-defined): 所有的範圍預設都會包含this和arguments。
2. 函數形參(Formal parameters): 函數有名字的形參會進入到函數體的範圍中。
3. 函式宣告(Function decalrations): 通過function foo() {}的形式。
4. 變數聲明(Variable declarations): 通過var foo;的形式。
總的來說,如果一個名稱已經被定義了,他絕不會被另一個擁有不用屬性的同名名稱覆蓋。
這就意味著,函式宣告比變數聲明具有更高的優先順序。但是這卻不意味著對這個名稱的賦值無效,僅僅是聲明的部分會被忽略而已。
內建的名稱arguments的行為有些怪異。他似乎是在形參之後,函式宣告之前被聲明。這就意味著名為arguments的形參會比內建的arguments具有更高的優先順序,即使這個形參是undefined。這是一個不好的特性,不要使用arguments作為形參。
任何地方試圖使用this作為一個標識都會引起語法錯誤,這是一個好的特性。
如果有多個同名形參,那位於列表最後的形參擁有最高的優先順序,即使它是undefined。
Name Function Expressions
你可以在函數運算式中給函數定義名稱,就像函式宣告的語句一樣。但這並不會使它成為一個函式宣告,並且這個名稱也不會被引入到範圍中,而且,函數體也不會被提升(hoist)。這裡有一些代碼可以說明我說的是什麼意思:
foo(); // TypeError "foo is not a function" bar(); // valid baz(); // TypeError "baz is not a function" spam(); // ReferenceError "spam is not defined" var foo = function () {}; // 匿名函數運算式(‘foo‘被提升) function bar() {}; // 函式宣告(‘bar‘和函數體被提升) var baz = function spam() {}; // 命名函數運算式(只有‘baz‘被提升) foo(); // valid bar(); // valid baz(); // valid spam(); // ReferenceError "spam is not defined"
How to Code With This Knowledge
現在你明白了範圍和提升,那麼這對編寫JavaScript代碼意味著什麼呢?最重要的一條是聲明變數時總是使用var語句。我強烈的建議你在每個範圍中都只在最頂端使用一個var。如果你強制自己這麼做,你永遠也不會被提升相關的問題困擾。儘管這麼做會使的跟蹤當前範圍實際聲明了哪些變數變得更加困難。我建議在JSLint使用onevar選項。如果你做了所有前面的建議,你的代碼看起來會是下面這樣:
/*jslint onevar: true [...] */ function foo(a, b, c) { var x = 1, bar, baz = "something"; }
我發現直接參考ECMAScript Standard (pdf)來理解這些東西是如何運作的總是很有用。下面是關於變數聲明和範圍的一段摘錄(section 12.2.2):
If the variable statement occurs inside a FunctionDeclaration, the variables are defined with function-local scope in that function, as described in section 10.1.3. Otherwise, they are defined with global scope (that is, they are created as members of the global object, as described in section 10.1.3) using property attributes { DontDelete }. Variables are created when the execution scope is entered. A Block does not define a new execution scope. Only Program and FunctionDeclaration produce a new scope. Variables are initialised to undefined when created. A variable with an Initialiser is assigned the value of its AssignmentExpression when the VariableStatement is executed, not when the variable is created.
JS Scoping and Hoisting