讀 arale 源碼之 class 篇

更新:讀 arale 源碼之 attribute 篇segmentfault

arale 是阿里、開源社區明星人物--玉伯,開發的一套組件,代碼至關優美,大讚玉伯的開源精神,我是您的粉絲。數組

這裏分享下我對這段源代碼的感悟,如有錯誤的地方,煩請指正。= ̄ω ̄=瀏覽器

先談談基於原型的繼承。

先看看 segementfault 上討論的一道題。app

function F() {}
Object.prototype.a = function() {}
Function.prototype.b = function() {}
var f = new F()
// F.a F.b f.a

F 能夠調用 a 和 b,由於 F 的原型鏈是這樣的。(直觀解釋:F 是 Function 實例,F 繼承自 Object)函數

F ----> Function.prototype ----> Object.prototype ----> null

//既 F.__proto__ === Function.prototype
// Function.prototype.__proto__ === Object.prototype
// Object.prototype.__proto__ === null

而 f 只能調用 a , f 的原型鏈是這樣的。(直觀解釋:f 是 F 的實例,一切皆對象,f 繼承自 Object)工具

f ----> F.prototype ----> Object.prototype ----> null

//既 f.__proto__ === F.prototype
// F.prototype.__proto__ === Object.prototype
// Object.prototype.__proto__ === null

在 f 的原型鏈上並無 Function.prototype . 所以訪問不到 b 。測試

注意,訪問原型對象 __proto__ 是非標準方法,ES5 標準方法是 Object.getPrototypeOf();this

到這裏,基於原型鏈的繼承已經很明顯了,只須要prototype

function Animal() {}

function Dog() {}

Dog.prototype.__proto__ = Animal.prototype;

var dog = new Dog();

// dog.__proto__ --> Dog.prototype;
// dog.__proto__.__proto__ --> Animal.prototype

基於 ES5 標準寫法是code

Dog.prototype = Object.create(Animal.prototype);

來看看 arale 的封裝

// 建立原型鏈
function Ctor() {};

var createProto = Object.__proto__ ? function(proto) {
  return {
    __proto__: proto
  }
} : function(proto) {
  Ctor.prototype = proto;
  return new Ctor();
}

有三種寫法能夠實現原型鏈繼承,可是我測試 new Ctor 是最慢的啊,Object.creaete 其次,__proto__ 是最快的。

function Ctor() {}

function getProto1(proto, c) {
  Ctor.prototype = proto;
  var o = new Ctor();
  o.constructor = c;
  return o;
}

function getProto2(proto, c) {
  return Object.create(proto, {
    constructor: {
      value: c
    }
  })
}

function getProto3(proto, c) {
  return {
    __proto__: proto,
    constructor: c
  }
}

接着往下看。。。

function Class(o) {
  if (!(this instanceof Class) && isFunction(o)) {
    return classify(o);
  }
}

function classify(cls) {
  cls.extend = Class.extend;
  cls.implement = implement;
  return cls;
}

這種寫法是,當不使用 new 關鍵字調用時,將參數 類化,如:

修改:是不支持 new 的方式調用。

function Animal() {}
Animal.prototype.talk = function() {}

//Class(Animal); Animal 擁有了 extend 和 implement 方法
var Dog = Class(Animal).extend({
  swim: function() {}
})

Class 的三個變種屬性 Extends Implements Statics

這三個屬性會作特殊處理

Class.Mutators = {
  // 繼承的方法,只支持單繼承
  Extends: function(parent) {
    var existed = this.prototype;
    // 創建原型鏈來實現繼承
    var proto = createProto(parent.prototype);
    mix(proto, existed);
    // 強制改變構造函數
    proto.constructor = this;
    this.prototype = proto;
    // 提供 superclass 語法糖,來調用父類屬性
    this.superclass = parent.prototype;
  },
  // 混入屬性,能夠混入多個類的屬性
  Implements: function(items) {
    // 將參數變成數組
    isArray(items) || (items = [ items ]);
    var proto = this.prototype, item;
    while (item = items.shift()) {
      // 不管參數是 類(Function),仍是 對象(Object),都混入。
      mix(proto, item.prototype || item);
    }
  },
  Statics: function(staticProperties) {
    // 直接混入靜態屬性。
    mix(this, staticProperties);
  }
}

再來看看 implement 方法, 它是用來混入屬性的。

三個變種屬性將被執行

function implement(properties) {
  var key, value;
  for (key in properties) {
    value = properties[key];
    if (Class.Mutators.hasOwnProperty(key)) {
      Class.Mutators[key].call(this, value);
    } else {
      this.prototype[key] = value;
    }
  }
}

好了,最關鍵的方法 Class.create 來了,它是用來建立類的,能夠指定父類。

Class.create = function(parent, properties) {
  // 若是沒有指定父類,父類就是 Class
  if (!isFunction(parent)) {
    properties = parent;
    parent = null;
  }
  properties || (properties = {});
  // 若是指定了 Extends 屬性, 父類就是它了
  parent || (parent = properties.Extends || Class);
  properties.Extends = parent;
  // 建立子類的構造函數
  function SubClass() {
    // 調用父類的構造函數
    parent.apply(this, arguments);
    // 僅調用自身的初始化方法,initialize
    if (this.constructor === SubClass && this.initialize) {
      this.initialize.apply(this, arguments);
    }
  }
  // 指定父類的狀況下,繼承父類的屬性
  if (parent !== Class) {
    Mix(SubClass, parent, parent.StaticsWhiteList);
  }
  // 爲子類添加實例屬性,三個特殊屬性,在這裏被執行
  implement.call(SubClass, properties);
  // 返回可繼續 繼承 的子類
  return classify(SubClass);
}

最後來看看繼承的方法 Class.extend ,被 classify 的類,均可以繼續建立子類。

Class.extend = function(properties) {
  properties || (properties = {});
  // 指定父類爲調用者
  properties.Extends = this;
  return Class.create(properties);
}

最後的最後,簡單介紹它的工具類,Helpers

// 屬性混合,增長白名單限制
function mix(r, s, wl) {
  for (var p in s) {
    // 最佳實踐:任何 for in 循環都要帶上 hasOwnProperty。除非你想遍歷原型
    if (s.hasOwnProperty(p)) {
      if (wl && indexOf(wl, p) === -1) continue;
      if (p !== "prototype") {
        r[p] = s[p];
      }
    }
  }
}

// [].indexOf 是 ES5 加入的,並不是全部瀏覽器都支持。
// 這裏沒有也不須要使用 polyfill 的方式。
var indexOf = Array.prototype.indexOf ? function(arr, item) {
  return arr.indexOf(item);
} : function(arr, item) {
  for (var i = 0, len = arr.length; i < len; i++) {
    if (arr[i] === item) {
      return i;
    }
  }
  return -1;
}

// 這個很簡單,只有 Object.prototype.toString 才能知道它的 [[class]]
var toString = Object.prototype.toString;
var isArray = Array.isArray || function(val) {
  return toString.call(val) === "[object Array]";
}
var isFunction = function(val) {
  return toString.call(val) === "[object Function]";
}
相關文章
相關標籤/搜索