JavaScript程式碼片段

來源:互聯網
上載者:User
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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.