DIV CSS 佈局教程網

深入 JavaScript:五道讓人跌破眼鏡的語言細節題
編輯:關於JavaScript     

Dmitry Baranovskiy 寫過一篇《So, you think you know JavaScript?》,Nicholas C. Zakas 也給了回應。兩篇文章裡的幾道小題目看起來平凡無奇,答案卻往往出人意料。以下是我的理解記錄——這些題目真正想考的不是冷知識,而是變數提升、函式表達式與 this 綁定這三個核心機制。

第一題:變數提升

if (!("a" in window)) {
  var a = 1;
}
alert(a);

翻成白話是:如果 window 上沒有 a 這個屬性,就宣告 a 並赋值為 1。你可能期望彈出 1,實際卻是 undefined。為什麼?

關鍵有三點。首先,JavaScript 的全域變數就是 window 的屬性,所以 var a = 1 等同於 window.a = 1,你可以用 "a" in window 來驗證。

其次,JavaScript 引擎在執行程式碼前會先掃描一遍,把變數宣告提升到作用域頂端:

alert("a" in window);
var a;

實際被解析成:

var a;
alert("a" in window);

所以結果是 true。

最後,宣告與赋值是兩個分開的步驟:

var a = 1;
/* 執行時其實被拆成 */
var a;
a = 1;

Nicholas 解釋這樣設計的理由是:如果在宣告時就順便初始化,可能影響程式碼執行時變數的值,導致意外結果。

把這些拼起來,第一題在執行時其實長這樣:

var a;                     // 自動前置的宣告,未初始化
if (!("a" in window)) {    // false!因為 a 已經存在了
  var a = 1;
}
alert(a);                  // 彈出 undefined

第二題:函式表達式不會提升

var a = 1, b = function a(x) { x && a(--x); };
alert(a);

理解第一題後,這題就好辦了。函式有兩種形態:函式宣告(function declaration)與函式表達式(function expression)。

function Daimaren(){ /* 函式宣告 */ }

var Daimaren = function(){ /* 函式表達式 */ }

所有函式宣告會被前置,函式表達式不會。看這兩段對照:

foo();   // 可以正常執行
function foo(){ alert("declaration"); }
var foo = function(){ alert("expression"); }
function foo(){ alert("declaration"); }
var foo = function(){ alert("expression"); }
foo();   // 執行的是 expression

第一段的 foo() 之所以能跑,是因為宣告被提升了;第二段則因為赋值在後,foo 已被表達式覆蓋。

回到原題:那個 function a(x) 是表達式,只作用於 b 的內部,並不影響外層的 a。所以答案恆為 1。

第三題:函式宣告優先於變數宣告

function a(x) { return x * 2; }
var a;
alert(a);

如果理解了提升機制,這題也不難:函式宣告的優先級高於普通的變數宣告,除非該變數被初始化。所以這裡會執行 function a 而忽略 var a。

對照一下:

function a(x) { return x * 2; }
var a = "1";
alert(a);

一旦有赋值,a 就變成字串 "1" 了。

第四題:arguments 是連動的

function b(x, y, a) {
  arguments[2] = 10;
  alert(a);
}
b(1, 2, 3);

答案是 10。這題考的是 arguments 物件。ECMA-262 第三版 10.1.8 節寫得很清楚:

For each non-negative integer, arg, less than the value of the length property, a property is created with name ToString(arg) and property attributes { DontEnum }. The initial value of this property is the value of the corresponding actual parameter supplied by the caller. The first actual parameter value corresponds to arg = 0, the second to arg = 1, and so on. In the case when arg is less than the number of formal parameters for the Function object, this property shares its value with the corresponding property of the activation object. This means that changing this property changes the corresponding property of the activation object and vice versa.

白話就是:arguments 的每個索引屬性,與對應的參數「共用同一個值」。改一邊,另一邊也跟著動。此例中 arguments[0] 對應 x、arguments[1] 對應 y、arguments[2] 對應 a。

看起來像陣列,但用 typeof 測會發現它是 object。連動關係可以這樣驗證:

function b(x, y, a) {
  arguments[2] = x;
  alert(a);   // 期望 3?但上一行已把它指向 x,所以是 1
}
b(1, 2, 3);

順帶一提,這個連動行為在 strict mode 下被移除了——arguments 與參數不再共用值。ES5 的設計者認為這種隱式連動太容易讓人誤解。

第五題:this 到底指向誰

function a() { alert(this); }
a.call(null);

Nicholas 說這是五題裡最簡單的一題。要理解它,先釐清 this 的指向規則。

當函式作為某物件的方法被呼叫時,this 指向該物件:

var o = {
  method: function() {
    alert(this === o);  // true
  }
};
o.method();

如果它不在任何物件裡,this 就指向 window:

function method() {
  alert(this === window);  // true
}
method();

再來是 call()。官方文件的解釋其實容易讓人迷糊:

call 方法 — 調用一個對象的一個方法,以另一個對象替換當前對象。
call([thisObj[, arg1[, arg2[, [,.argN]]]]])
thisObj:將被用作當前對象的對象。如果沒有提供 thisObj 參數,那麼 Global 對象被用作 thisObj。

Nicholas 的說法直白得多:

The call() method executes a function as if it were a method of another object

看個例子:

function add(a, b) { alert(a + b); }
function sub(a, b) { alert(a - b); }

add.call(sub, 3, 1);   // 4

第一個參數決定 this 是誰,後面的是一般參數。所以它等同於:

add.call(sub, 3, 1) == add(3, 1)

回到原題,a.call(null) 就相當於直接呼叫 a()。this 指向的是 a 這個函式物件本身,於是 alert 出來的會是函式的內容。

(在非 strict mode 下,傳入 null 會被轉換為全域物件,所以嚴格說 alert 出的是 window;在 strict mode 下 this 才會保持為 null。這個細節在 ES5 之後有了明確規範。)

這些題目該拿來面試嗎?

Nicholas 提到,有人喜歡拿這種題目當面試題,他認為這對面試者並不尊重,也沒什麼用處——因為這些錯誤或細節在日常工作中未必遇得到,就像面試空服員卻要人家解釋噴射引擎動力原理一樣。

這個看法我很贊同。這類知識適合當作理解語言機制的鑰匙,拿來細讀、拿來寫成文章都可以;但拿來故意刁難人,就有點本末倒置了。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved