【轉】require.js學習筆記(一)

來源:互聯網
上載者:User

標籤:blog   http   io   ar   使用   java   for   sp   檔案   

一、立即執行函數
for (var i = 0; i < elems.length; i++) {    (function (lockedInIndex) {          elems[i].addEventListener(‘click‘, function (e) {            e.preventDefault();            alert(‘I am link #‘ + lockedInIndex);        }, ‘false‘);    })(i); //入參}
使用立即執行函數,可以達到不暴露私人成員的目的
var module1 = (function(){    var _count = 0;    var m1 = function(){      //...    };    var m2 = function(){      //...    };    return {      m1 : m1,      m2 : m2    };  })();  //無法讀取_count    
 對比立即執行函數
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title></head><body><script> var a = function() { alert(12) var _count=1;        var m1 = function(){      alert(1);    };    var m2 = function(){      alert(2);    };    return {      m1 : m1,      m2 : m2    }; };     var b = a(); b.m1(); var a2 = (function() { alert(12); var _count=1;        var m1 = function(){      alert(1);    };    var m2 = function(){      alert(2);    };    return {      m1 : m1,      m2 : m2    }; })(); a2.m2(); </script></body></html>
 二、模組規範目前主要的模組規範有commonJS與AMD 1.commonJScommonJS是伺服器端模組規範,nodeJs遵循此規範。因為服務端JS檔案存放於本地,載入速度快,所以其載入模組(一個檔案即一個模組)方式為同步載入,不適用於瀏覽器。
function foobar(){        this.foo = function(){                console.log(‘Hello foo‘);        }        this.bar = function(){                console.log(‘Hello bar‘);        }} exports.foobar = foobar; //通過export實現與外部通訊
var foobar = require(‘./foobar‘).foobar,    test   = new foobar(); test.bar(); 
2.AMD採用非同步載入模組,載入完成後通過回呼函數實現相應操作,適用與瀏覽器。
require([‘math‘], function (math) {    math.add(2, 3);  });


    原文地址:http://www.ruanyifeng.com/blog/2012/10/javascript_module.html http://www.cnblogs.com/TomXu/archive/2011/12/31/2289423.htmlhttp://javascript.ruanyifeng.com/nodejs/commonjs.html

【轉】require.js學習筆記(一)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.