Underscore.js 分析

來源:互聯網
上載者:User

標籤:style   blog   io   ar   color   sp   for   java   on   

Underscore.js的源碼和適合第一次看源碼的人,因為檔案比較小,而且沒有依賴,讀起來比較輕鬆。代碼寫的還很是很簡練的。

我看的是1.7的源碼,下面說說我覺得比較有意思的幾個地方

1. 

_.isUndefined = function(obj) {    return obj === void 0;};

代碼裡好幾個地方都用到了void 0,而不是undefined判斷一個object是不是undefined。據說這樣是因為有些瀏覽器允許改變undefined的值。比如undefined = 1

2.

以前用jQuery的時候就用到過noConflict,一直在好奇是怎麼實現的。原來Underscore.js裡的實現這麼簡單

var root = this;var previousUnderscore = root._;_.noConflict = function() {    root._ = previousUnderscore;    return this;};

3. 

Underscore.js支援兩種方式調用,一種是直接用_.func(params)調用,還有以類似oop的方式調用

_.each([‘a‘, ‘b‘, ‘c‘], function(element, index){    console.log(element);});_([‘a‘, ‘b‘, ‘c‘]).each(function(element, index){    console.log(element);});

這是怎麼做到的呢?

首先,定義了_下面的函數,比如

  _.each = _.forEach = function(obj, iteratee, context) {    if (obj == null) return obj;    iteratee = createCallback(iteratee, context);    var i, length = obj.length;    if (length === +length) {      for (i = 0; i < length; i++) {        iteratee(obj[i], i, obj);      }    } else {      var keys = _.keys(obj);      for (i = 0, length = keys.length; i < length; i++) {        iteratee(obj[keys[i]], keys[i], obj);      }    }    return obj;  };

如果把javascript中的對象看作類,這樣的定義就類似定義了類 ‘_’的static成員函數,直接通過 _.func就可以調用。但是 類‘_‘的執行個體 new _(),是不能調用的。

 

只是oop主要靠下面的兩個函數

 var _ = function(obj) {    if (obj instanceof _) return obj;    if (!(this instanceof _)) return new _(obj);    this._wrapped = obj;  };  // Add your own custom functions to the Underscore object.  _.mixin = function(obj) {    _.each(_.functions(obj), function(name) {      var func = _[name] = obj[name];      _.prototype[name] = function() {        var args = [this._wrapped];        push.apply(args, arguments);        return result.call(this, func.apply(_, args));      };    });  };  // Add all of the Underscore functions to the wrapper object.  _.mixin(_);

先看第一個函數,當調用_([‘a‘, ‘b‘, ‘c‘])的時候,第一個函數會執行。它做的事情就是把一個obj變成了‘_‘的一個執行個體(new _()),並且把obj存到該執行個體的_wrapped中。

該函數的實現也很有意思。當調用_[‘a‘, ‘b‘, ‘c‘]的時候,第一次執行到第二句,this是全域的window, 因此if(!(this instanceof _)) 成立,所以執行new _(obj),這時候第二次進入該函數,此時的this已經是新的_ instance執行個體,因此直接執行到了第三行,即把this_wrapped賦值為obj。

TBC...

Underscore.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.