1,模版替換(跟Crockford學的)
var template = '<table border="{ border }">' + '<tr><th>Last</th><td>{ last } </td></tr>' + '<tr><th>First</th><td>{ first }</td></tr>' + '</table>'var data = { first: 'Jerry', last: 'Chou', border: 2}mydiv.innerHTML = template.supplant(data);//實現if(typeof String.prototype.supplant !== 'function'){ String.prototype.supplant = function (o){ return this.replace(/{ ([^{}]) }/g, function(a, b){var r = o[b];return typeof r === 'string' ? r : a; } }}
2,類比塊範圍(Block Scope)
我們知道在JavaScript中沒有範圍(block scope),所有函數體內定義的變數都會被hoisting(即提到函數的頂部)。為了類比類似C/Java/C#語言中的塊範圍(block scope),我們可以使用以下程式碼片段。這也是我們看別人寫的類庫比如JQuery時常見到的形式——定義後立即調用。
(function(){ //bla..bla}());
比如下面的代碼使用該技術類比了一個塊範圍:
function foo() {var x = 1; if (x) { (function () { var x = 2; // some other code }()); } // x is still 1.}
至於為什麼定義了一個函數範圍就立即調用?因為函數的定義並不會執行函數體上的代碼,當們在函數定義後加上(),進行調用時,才會執行函數體內的代碼——更嚴謹的說法是:函數在調用時(加上”()”)才會建立執行環境(Execution Context)。
參考:[翻譯]JavaScript Scoping and Hoisting