下面是官方的一個例子:
// Shape - 父類
function Shape() {
this.x = 0;
this.y = 0;
}
Shape.prototype.move = function(x, y) {
this.x += x;
this.y += y;
console.info("Shape moved.");
};
// Rectangle - 子類
function Rectangle() {
Shape.call(this); // 呼叫父類構造器
}
Rectangle.prototype = Object.create(Shape.prototype);
var rect = new Rectangle();
rect instanceof Rectangle // true
rect instanceof Shape // true
rect.move(1, 1); // Outputs, "Shape moved."
此時 Rectangle 原型的 constructor 指向父類,如需使用自身的構造,手動指定即可:
Rectangle.prototype.constructor = Rectangle;
語法:util.inherits(constructor, superConstructor)
const util = require('util');
const EventEmitter = require('events');
function MyStream() {
EventEmitter.call(this);
}
util.inherits(MyStream, EventEmitter);
MyStream.prototype.write = function(data) {
this.emit('data', data);
}
var stream = new MyStream();
console.log(stream instanceof EventEmitter); // true
console.log(MyStream.super_ === EventEmitter); // true
stream.on('data', (data) => {
console.log(`Received data: "${data}"`);
})
stream.write('It works!'); // Received data: "It works!"
它的原始碼其實用了 ES6 的新特性:
exports.inherits = function(ctor, superCtor) {
if (ctor === undefined || ctor === null)
throw new TypeError('The constructor to "inherits" must not be null or undefined');
if (superCtor === undefined || superCtor === null)
throw new TypeError('The super constructor to "inherits" must not be null or undefined');
if (superCtor.prototype === undefined)
throw new TypeError('The super constructor to "inherits" must have a prototype');
ctor.super_ = superCtor;
Object.setPrototypeOf(ctor.prototype, superCtor.prototype);
};
其中 Object.setPrototypeOf 即為 ES6 新特性,它會把一個指定物件(obj)的原型設定為另一個物件或 null:
Object.setPrototypeOf({}, null); // 將原型設為 null
這個方法在舊環境下的實現可以這樣模擬:
Object.setPrototypeOf = Object.setPrototypeOf || function (obj, proto) {
obj.__proto__ = proto;
return obj;
}
熟悉 Java 的同學應該對這個關鍵字非常熟悉。ES6 新加入的 class 關鍵字是語法糖,本質還是函式。下面的例子定義了一個名為 Polygon 的類,然後定義了一個繼承於 Polygon 的類 Square。注意到構造器中使用的 super()——它只能在構造器中使用,且必須在 this 可用之前呼叫。
class Polygon {
constructor(height, width) {
this.name = 'Polygon';
this.height = height;
this.width = width;
}
}
class Square extends Polygon {
constructor(length) {
super(length, length);
this.name = 'Square';
}
}
使用關鍵字後,就不用各種手動設定原型了,關鍵字已經把這些細節封裝好,快捷又方便。