DIV CSS 佈局教程網

JavaScript 代碼復用模式(避免篇):六種繼承寫法為何該被放棄
編輯:JavaScript基礎知識     

任何工程都繞不開代碼復用,否則每做一個新功能都要從零敲起,項目根本推不動。但復用本身也有好壞之分:有些手法看著能跑,實則埋著坑。本篇整理六種應當避免的繼承寫法,逐一說明它們各自的短板;下一篇再談值得推薦的方案。

模式一:默認模式

最直覺的繼承寫法,是把父構造函數的實例直接賦給子類型的原型。

function inherit(C, P) {
  C.prototype = new P();
}

function Parent(name) {
  this.name = name || 'Adam';
}
Parent.prototype.say = function () {
  return this.name;
};

function Child(name) {}

inherit(Child, Parent);

var kid = new Child();
console.log(kid.say()); // "Adam"

var kiddo = new Child();
kiddo.name = "Patrick";
console.log(kiddo.say()); // "Patrick"

問題出在參數上。子類型的構造函數根本沒有把參數往父傳的通道:

var s = new Child('Seth');
console.log(s.say()); // "Adam",'Seth' 被無視了

參數傳不進去,這個模式在實戰中基本就報廢了。

模式二:借用構造函數

換個思路:不繼承原型,而是在子構造函數裡呼叫父構造函數,把 this 和參數一起傳過去。

function Parent(name) {
  this.name = name || 'Adam';
}
Parent.prototype.say = function () {
  return this.name;
};

function Child(name) {
  Parent.apply(this, arguments);
}

var kid = new Child("Patrick");
console.log(kid.name);        // "Patrick",參數通了
console.log(typeof kid.say);  // "undefined",原型方法沒繼承過來

缺點正好和上個模式互補:參數通了,原型上的方法卻丟了。只繼承實例屬性、不繼承原型,等於只拿了一半。

模式三:借用構造函數並設置原型

很自然會想到把兩者相加:

function Parent(name) {
  this.name = name || 'Adam';
}
Parent.prototype.say = function () {
  return this.name;
};

function Child(name) {
  Parent.apply(this, arguments);
}
Child.prototype = new Parent();

var kid = new Child("Patrick");
console.log(kid.name);        // "Patrick"
console.log(typeof kid.say);  // "function"
console.log(kid.say());       // "Patrick"

delete kid.name;
console.log(kid.say());       // "Adam",原型鏈上還留著一份

功能齊全了,但代價是父構造函數被執行了兩次:一次在 apply,一次在 new Parent()。若父構造函數裡有 DOM 操作、網絡請求或計數遞增,這個副作用會變得很難查。同時原型上還殘留了一份用不到的實例屬性。

模式四:共享原型

既然問題出在原型,那就乾脆讓父子共用同一個原型對象。

function inherit(C, P) {
  C.prototype = P.prototype;
}

function Parent(name) {
  this.name = name || 'Adam';
}
Parent.prototype.say = function () {
  return this.name;
};

function Child(name) {}

inherit(Child, Parent);

var kid = new Child('Patrick');
console.log(kid.name);       // undefined,參數依舊沒接到
console.log(typeof kid.say); // "function"

kid.name = 'Patrick';
console.log(kid.say());      // "Patrick"

省下了指針開銷,但參數問題原封不動,而且父子共享原型意味著任何一方往原型上加東西都會影響另一方,耦合比原來更緊了。

模式五:臨時構造函數

這個模式引入一個空的臨時構造函數充當墊片,讓子原型指向它的實例,從而不觸發父構造函數的執行。

var inherit = (function () {
  var F = function () {};
  return function (C, P) {
    F.prototype = P.prototype;
    C.prototype = new F();
    C.uber = P.prototype;              // 保留父原型的便捷引用
    C.prototype.constructor = C;       // 修正被覆蓋掉的 constructor
  };
}());

function Parent(name) {
  this.name = name || 'Adam';
}
Parent.prototype.say = function () {
  return this.name;
};

function Child(name) {}

inherit(Child, Parent);

var kid = new Child();
console.log(kid.name);              // undefined
console.log(typeof kid.say);        // "function"
kid.name = 'Patrick';
console.log(kid.say());             // "Patrick"

var kid2 = new Child("Tom");
console.log(kid2.name);                    // undefined
console.log(kid.constructor.name);         // "Child"
console.log(kid.constructor === Parent);   // false

原型鏈乾淨了,性能也回來了,但子構造函數依然收不到參數。它是後續推薦篇的基礎,只是單獨使用仍不完整。

模式六:klass

最後這個模式試圖把類繼承的語法完整搬到 JavaScript 上:一個函數搞定繼承、構造函數鏈調用和方法批量掛載。

var klass = function (Parent, props) {
  var Child, F, i;

  // 1. 新構造函數:依序呼叫父類與自身的 __construct
  Child = function () {
    if (Child.uber && Child.uber.hasOwnProperty("__construct")) {
      Child.uber.__construct.apply(this, arguments);
    }
    if (Child.prototype.hasOwnProperty("__construct")) {
      Child.prototype.__construct.apply(this, arguments);
    }
  };

  // 2. 用臨時函數建立原型鏈
  Parent = Parent || Object;
  F = function () {};
  F.prototype = Parent.prototype;
  Child.prototype = new F();
  Child.uber = Parent.prototype;
  Child.prototype.constructor = Child;

  // 3. 批量拷貝方法
  for (i in props) {
    if (props.hasOwnProperty(i)) {
      Child.prototype[i] = props[i];
    }
  }

  return Child;
};

用法看起來確實很像正統的類:

var Man = klass(null, {
  __construct: function (what) {
    console.log("Man's constructor");
    this.name = what;
  },
  getName: function () {
    return this.name;
  }
});

var first = new Man('Adam'); // logs "Man's constructor"
first.getName();             // "Adam"

var SuperMan = klass(Man, {
  __construct: function (what) {
    console.log("SuperMan's constructor");
  },
  getName: function () {
    var name = SuperMan.uber.getName.call(this);
    return "I am " + name;
  }
});

var clark = new SuperMan('Clark Kent');
clark.getName();                  // "I am Clark Kent"
console.log(clark instanceof Man);      // true
console.log(clark instanceof SuperMan); // true

功能上無懈可擊,問題是它在 JavaScript 裡顯得格外異質:__construct 這種約定、用 uber 模擬 super、靠字符串屬性名做鉤子,每一處都在跟語言本身的習慣作對。ES6 有了 class 語法之後,這種手工方案就更沒有存在必要了。

小結

六個模式各自解決了一部分問題,也各自留下了新的短板:默認模式丟參數,借用構造函數丟原型,兩者相加則父構造函數跑兩次,共享原型耦合過緊,臨時構造函數仍舊丟參數,klass 則把語言風格擰得面目全非。了解它們的破綻有現實意義——遺留代碼裡到處都是這些寫法,讀得懂它們在哪裡會出問題,才能在維護時不去踩同一個坑。下一篇我們看推薦篇。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved