DIV CSS 佈局教程網

ES6 class 完整導覽:從基本定義、靜態成員到多重繼承
編輯:關於JavaScript     

ES6(ECMAScript 2015)為 JavaScript 帶來了 class 語法。它並不是全新的物件導向模型,而是 ES5 原型繼承的語法糖,寫起來更乾淨,繼承也更直覺。想真正理解它背後在做什麼,先熟悉 ES5 的原型繼承會很有幫助。

定義一個類別

用 class 定義的類別預設都有一個 constructor,那是它的建構函式主體,函式體內的 this 指向新產生的實例;寫在類別裡的方法則掛在原型上。

 "use strict";
 class Person {
   constructor(name) {
     this.name = name;
   }
   say () {
     console.log("say hi");
   }
 };
 new Person().say(); // 輸出 say hi

注意:ES6 的類別不存在函式宣告提升,必須先宣告再使用。把上一段的最後一行移到最前面,就會直接拋錯:

 "use strict";
 new Person().say(); // ReferenceError
 class Person {
   constructor(name) {
     this.name = name;
   }
   say () {
     console.log("say hi");
   }
 };

靜態方法

在方法前加上 static,它就成為靜態方法,直接挂在類別上,與原型無關:

 "use strict";
 class Person {
   constructor(name) {
     this.name = name;
   }
   static say () {
     console.log("say hi");
   }
 };
 Person.say();

原型方法

直接寫「方法名 () {}」就完成,括號內是參數列,大括號內是程式碼區塊。ES5 得寫成 建構函式.prototype.方法名 = function(){},相比之下 ES6 的寫法接近 Java、C#:

 "use strict";
 class Person {
   constructor(name) {
     this.name = name;
   }
   say () { console.log("say hi"); }
   sing () { console.log("lalalalala"); }
 };
 new Person().say();  // say hi
 new Person().sing(); // lalalalala

靜態屬性與原型屬性

靜態屬性只能在類別定義完成之後補上,語法上確實有點不順:

 "use strict";
 class Person {
   constructor(name) {
     this.name = name;
   }
 };
 Person.hands = 2;
 console.log(Person.hands);

原型上則改用 getter / setter 來控制存取:

 class Person {
   constructor(_name) {
     this._name = _name;
   }
   get name() { return this._name; }
   set name(_name) { this._name = _name; }
 }
 var p = new Person();
 p.name = "heheda";
 console.log(p.name);  // heheda
 console.log(p._name); // heheda

若想要每個實例都有一份自己的屬性,直接寫在 constructor 裡即可,子類也會透過 super() 繼承到:

 class Person {
   constructor() {
     this.name = "default";
   }
 }
 class Man extends Person {
   constructor() {
     super();
   }
 }
 console.log(new Man().name);

類別繼承 extends

ES5 早就有繼承,但寫法繞來繞去;ES6 的 extends 本質上仍是原型繼承的封裝,只是清爽很多:

 "use strict";
 class Person {
   constructor(name) {
     this.name = name;
   }
   say () {
     console.log("say hi");
     return this;
   }
 };
 class SMan extends Person {
   constructor (name, power) {
     super(name);
     this.superPower = power;
   }
   show () {
     console.log(this.superPower);
     return this;
   }
 }
 console.log(new SMan("Clark", "pee").show().say().name); // pee / say hi / Clark

使用繼承時,子類建構式中必須呼叫 super(),否則會出錯。super 有三種角色:作為建構函式直接呼叫、作為父類實例使用、以及在子類靜態方法中呼叫父類的靜態方法。

ES5 常見的繼承是把子類原型設為父類實例:

 var Sup = function() { this.sub = true; };
 Sup.prototype.protoSup = { sup: "sup" };
 var Sub = function() { this.sub = true; };
 Sub.prototype = new Sup();          // 繼承原型
 Sub.prototype.constructor = Sub;    // 修正 constructor;

ES6 的處理更細緻,結合了呼叫式繼承與原型繼承,不會互相干擾:

 var Sup = function() { this.sub = true; };
 var Sub = function() {
   this.sup = true;
   Sup.apply(this);   // 繼承 this 上的屬性與方法
 };
 Sub.__proto__ = Sup; // 繼承 Sup 的靜態屬性
 Sub.prototype = Object.create(Sup.prototype, {
   constructor: { value: Sub, enumerable: false, writable: true, configurable: true }
 });                  // 繼承原型屬性並覆寫 constructor;

用 ES5 反推 ES6 繼承的實作

有了 Babel 這類轉碼器,我們可以反過來看 ES6 的繼承究竟被編譯成什麼:

 var _createClass = function () {
   function defineProperties(target, props) {
     for (var i = 0; i < props.length; i++) {
       var descriptor = props[i];
       descriptor.enumerable = descriptor.enumerable || false;
       descriptor.configurable = true;
       if ("value" in descriptor) descriptor.writable = true;
       Object.defineProperty(target, descriptor.key, descriptor);
     }
   }
   return function (Constructor, protoProps, staticProps) {
     if (protoProps) defineProperties(Constructor.prototype, protoProps);
     if (staticProps) defineProperties(Constructor, staticProps);
     return Constructor;
   };
 }();
 function _classCallCheck(instance, Constructor) {
   if (!(instance instanceof Constructor)) {
     throw new TypeError("Cannot call a class as a function");
   }
 }
 function _possibleConstructorReturn(self, call) {
   if (!self) {
     throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
   }
   return call && (typeof call === "object" || typeof call === "function") ? call : self;
 }
 // _inherits 負責原型繼承與父類靜態屬性的繼承
 function _inherits(subClass, superClass) {
   if (typeof superClass !== "function" && superClass !== null) {
     throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
   }
   subClass.prototype = Object.create(superClass && superClass.prototype, {
     constructor: { value: subClass, enumerable: false, writable: true, configurable: true }
   });
   if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
 }
 var Person = function () {
   function Person(name) {
     _classCallCheck(this, Person);
     this.name = name;
   }
   _createClass(Person, [{ key: "say", value: function say() {
     console.log("say hi");
     return this;
   } }]);
   return Person;
 }();
 var SMan = function (_Person) {
   _inherits(SMan, _Person);
   function SMan(name, power) {
     _classCallCheck(this, SMan);
     var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(SMan).call(this, name));
     _this.superPower = power;
     return _this;
   }
   _createClass(SMan, [{ key: "show", value: function show() {
     console.log(this.superPower);
     return this;
   } }]);
   return SMan;
 }(Person);
 console.log(new SMan("Clark", "pee").show().say().name);

從這裡可以清楚看到幾件事:_classCallCheck 模擬了「類別不能當函式呼叫」的限制,_createClass 用 Object.defineProperty 把方法掛到原型與建構函式上,而 _inherits 則同時處理了原型鏈與建構函式之間的 __proto__ 連結。

多重繼承:用 mix-in 模擬

JavaScript 不支援多重繼承,但可以透過 mix-in 把多個類別的成員複製到同一個類別上,寫法為 class Sub extends mix(obj0, obj1, obj2):

 <html>
 <head><meta charset="utf-8"></head>
 <body>
 <script>
 "use strict";
 function mix(...mixins) {
   class Mix {}
   for (let mixin of mixins) {
     copyProperties(Mix, mixin);
     copyProperties(Mix.prototype, mixin.prototype);
   }
   return Mix;
 }
 function copyProperties(target, source) {
   for (let key of Reflect.ownKeys(source)) {
     if (key !== "constructor" && key !== "prototype" && key !== "name") {
       let desc = Object.getOwnPropertyDescriptor(source, key);
       Object.defineProperty(target, key, desc);
     }
   }
 }
 class Man { work () { console.log("working"); } }
 class Woman { say () { console.log("saying"); } }
 class SuperMan extends mix(Man, Woman) {
   constructor () { super(); }
 }
 var sm = new SuperMan();
 sm.work();
 sm.say();
 // 實際上不存在繼承關係,只是把屬性複製過來
 console.log(sm instanceof Man);   // false
 console.log(sm instanceof Woman); // false
 </script>
 </body>
 </html>

關鍵在於 mix-in 走的是「複製」而非「連結原型鏈」,所以 instanceof 判斷不會成立——這也是它與真正的繼承最直觀的差別。

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