JavaScript 有許多內部屬性與方法,一般情況下只有引擎自己能用。但規則總有例外,Mozilla 的 JavaScript 引擎就是其中之一:SpiderMonkey 與 Rhino 都開放了一些介面讓我們碰觸這些內部機制,用得好不僅能讓程式更健壯,還能做出相當有意思的功能,本文介紹的 __noSuchMethod__() 就是這樣一個例子。
著作權聲明
本文譯自 Nicholas C. Zakas 於 2009 年 2 月 17 日發表的《Mozilla JavaScript extension: __noSuchMethod__》,為經原作者授權的中文版翻譯。譯者在準確性上盡了最大努力,並承諾內容忠於原文,若仍有疏漏或不宜之處,歡迎指正。譯註屬非正式內容,僅代表譯者個人觀點。
和其它瀏覽器相比,Mozilla 的 JavaScript 引擎總有幾分與眾不同。SpiderMonkey 與以 Java 實作的 Rhino 都提供了不少擴充特性,其中一項就是原生物件上的 __noSuchMethod__() 方法。
在多數引擎中,呼叫不存在的方法只會直接丟出錯誤;而在 Mozilla 引擎裡這只是預設行為,我們可以覆寫物件的 __noSuchMethod__() 來重新定義它——當有人嘗試呼叫該物件上不存在的函式時,就會轉而觸發這個方法。
被呼叫時,__noSuchMethod__() 會收到兩個參數:未使用的方法名稱,以及對應的參數陣列。要注意這個參數必須是 Array 物件而非 arguments;即使沒有傳參數,也要給一個空陣列。
// 注意:以下程式碼僅能在使用 SpiderMonkey 或 Rhino 的瀏覽器中正確解析 var person = { name: "Nicholas", __noSuchMethod__: function(name, args){ alert("Method called '" + name + "' executed with arguments [" + args + "]"); } } //"Method called 'sayName' executed with arguments []" person.sayName(); //"Method called 'phone' executed with arguments [Mike]" person.phone("Mike");
這裡定義了一個 person 物件並覆寫它的 __noSuchMethod__()。當呼叫 sayName() 與 phone() 時,由於這兩個方法都不存在,__noSuchMethod__() 便會被自動觸發,於是原本會中斷的錯誤變成了可以被攔下來處理的訊息——範例中的處理方式就是把方法名與參數直接印出來。
話說回來,在執行期才發現方法未定義,本來就不該是正常開發流程的一部分,那根本是自找麻煩。所以就一般情境而言,這個特性似乎沒什麼用武之地;但它確實開了一扇門,讓我們能做出一些有趣的動態工具。舉例來說,做一個可以輸出合法 XHTML 的物件:
function HTMLWriter(){ this._work = []; } HTMLWriter.prototype = { escape: function (text){ return text.replace(/[><"&]/g, function(c){ switch(c){ case ">": return ">"; case "<": return "<"; case "\"": return """; case "&": return "&"; } }); }, startTag: function(tagName, attributes){ this._work.push("<" + tagName); if (attributes){ var name, value; for (name in attributes){ if (attributes.hasOwnProperty(name)){ value = this.escape(attributes[name]); this._work.push(" " + name + "=\"" + value + "\""); } } } this._work.push(">"); }, text: function(text){ this._work.push(this.escape(text)); }, endTag: function(tagName){ this._work.push(""); }, toString: function(){ return this._work.join(""); } }; var writer = new HTMLWriter(); writer.startTag("html"); writer.startTag("head"); writer.startTag("title"); writer.text("Example & Test"); writer.endTag("title"); writer.endTag("head"); writer.startTag("body", { style: "background-color: red" }); writer.text("Hello world!"); writer.endTag("body"); writer.endTag("html"); alert(writer);
這裡只用了 startTag()、endTag()、text() 三個方法就完成任務,但呼叫端寫起來實在冗長。如果換個思路:不寫這三個方法,而是替每個合法 XHTML 標籤各做一個同名方法,呼叫端就會變成下面這樣,可讀性立刻提升:
var writer = new HTMLWriter(); var result = writer.html() .head().title().text("Example & Test").xtitle().xhead() .body().text("Hello world!").xbody() .xhtml().toString();
問題是每個標籤的實作幾乎一樣,難不成要為 HTMLWriter 複製一長串幾乎相同的函式?那無疑是巨大的浪費。這正是 __noSuchMethod__() 真正能發揮價值的地方:
function HTMLWriter(){ this._work = []; } HTMLWriter.prototype = { escape: function (text){ return text.replace(/[><"&]/g, function(c){ switch(c){ case ">": return ">"; case "<": return "<"; case "\"": return """; case "&": return "&"; } }); }, text: function(text){ this._work.push(this.escape(text)); return this; }, toString: function(){ return this._work.join(""); }, __noSuchMethod__: function(name, args){ var tags = [ "a", "abbr", "acronym", "address", "applet", "area", "b", "base", "basefont", "bdo", "big", "blockquote", "body", "br", "button", "caption", "center", "cite", "code", "col", "colgroup", "dd", "del", "dir", "div", "dfn", "dl", "dt", "em", "fieldset", "font", "form", "frame", "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "hr", "html", "i", "iframe", "img", "input", "ins", "isindex", "kbd", "label", "legend", "li", "link", "map", "menu", "meta", "noframes", "noscript", "object", "ol", "optgroup", "option", "p", "param", "pre", "q", "s", "samp", "script", "select", "small", "span", "strike", "strong", "style", "sub", "sup", "table", "tbody", "td", "textarea", "tfoot", "th", "thead", "title", "tr", "tt", "u", "ul", "var" ]; var closeTag = (name.charAt(0) == "x"), tagName = closeTag ? name.substring(1) : name; if (tags.indexOf(tagName) > -1){ if (!closeTag){ this._work.push("<" + tagName); if (args.length){ var attributes = args[0], name, value; for (name in attributes){ if (attributes.hasOwnProperty(name)){ value = this.escape(attributes[name]); this._work.push(" " + name + "=\"" + value + "\""); } } } this._work.push(">"); } else { this._work.push(""); } return this; } else { throw new Error("Method '" + name + "' is undefined."); } } };
重點全在 __noSuchMethod__() 裡:它帶著一份合法 XHTML 標籤清單,用來判斷被呼叫的方法名是否有效。若方法名以 “x” 開頭,就視為關閉標籤,並把首字母去掉後再比對;比對時使用 Mozilla 的陣列擴充 indexOf()。方法名不在清單中就丟出錯誤,否則組出對應的標籤字串。由於標籤清單只是一個陣列,要增減「方法」只要改這份清單即可,不必動任何程式結構。
很明顯,這個特性無法跨瀏覽器,不適合用在一般情境。但對專門面向 Mozilla 引擎(例如 Firefox)的應用而言,它確實開了一扇相當神奇的大門——特別是在打造動態介面時,__noSuchMethod__() 會是很俐落的工具。