mass Framework決定用less作為自己的CSS重用工具,決定好好學習一下它的源碼,說不定以後用mass Framework重寫它。
一上來是個經典結構:自動執行函數
(function (window, undefined) {})(window)
接著是載入器相關的內容
function require(arg) { return window.less[arg.split('/')[1]]; }; // amd.js //如果引入AMD的載入器,則把它當成一個AMD模組 if (typeof define === "function" && define.amd) { define("less", [], function () { return less; } ); }
再接著ecma262v5的語言補丁,我們總得支援IE6
if (!Array.isArray) { Array.isArray = function(obj) { return Object.prototype.toString.call(obj) === "[object Array]" || (obj instanceof Array); }; } if (!Array.prototype.forEach) { Array.prototype.forEach = function(block, thisObject) { var len = this.length >>> 0; for (var i = 0; i >> 0; var res = new Array(len); var thisp = arguments[1]; for (var i = 0; i >> 0; var i = 0; // no value to return if no initial value and an empty array if (len === 0 && arguments.length === 1) throw new TypeError(); if (arguments.length >= 2) { var rv = arguments[1]; } else { do { if (i in this) { rv = this[i++]; break; } // if array contains no values, no initial value to return if (++i >= len) throw new TypeError(); } while (true); } for (; i = length) return -1; if (i 接著是宿主環境檢測與把命名空間放到全域變數下:
var less, tree; if (typeof environment === "object" && ({}).toString.call(environment) === "[object Environment]") { //如果是在Rhino環境中 // Details on how to detect Rhino: https://github.com/ringo/ringojs/issues/88 if (typeof(window) === 'undefined') { less = {} } else { less = window.less = {} } tree = less.tree = {}; less.mode = 'rhino'; } else if (typeof(window) === 'undefined') { //如果是在node.js環境中 less = exports, //我們可以把幾個模組合并到一個JS檔案中,因此如果是打包了,是調當前檔案中的tree模組 tree = require('./tree'); less.mode = 'node'; } else { //如果是在瀏覽器環境中 if (typeof(window.less) === 'undefined') { window.less = {} } less = window.less, tree = window.less.tree = {}; less.mode = 'browser'; }下面就是正式的解析器的內容了最主要的用法是new(less.Parser)().parse,是沒有傳參,env可能是為了向前相容。 由於方法間的連聯太頻繁,從原型上調來調去太低效,改成如下結構
// function (){ /*內部方法與對象*/ return parser = {} }
待續!