下面是官网的一个例子java
//Shape - superclass 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 - subclass function Rectangle() { Shape.call(this); //call super constructor. } 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;
utilities
工具包自带的util.inherites
语法工具
util.inherits(constructor, superConstructor)
例子ui
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
的新特性,咱们瞅一瞅this
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新特性,将一个指定的对象的原型设置为另外一个对象或者nullprototype
语法code
Object.setPrototypeOf(obj, prototype)
obj
为将要被设置原型的一个对象prototype
为obj
新的原型(能够是一个对象或者null).对象
若是设置成null
,即为以下示例继承
Object.setPrototypeOf({}, null);
感受setPrototypeOf
真是人如其名啊,专门搞prototype
来玩。
那么这个玩意又是如何实现的呢?此时须要借助宗师__proto__
原型
Object.setPrototypeOf = Object.setPrototypeOf || function (obj, proto) { obj.__proto__ = proto; return obj; }
即把proto
赋给obj.__proto__
就行了。
extends
关键字熟悉java
的同窗应该很是熟悉这个关键字,java中的继承都是靠它实现的。
ES6新加入的class关键字是语法糖,本质仍是函数.
使用extends修改以前util.inherits
的例子,将会更简单
const EventEmitter = require('events'); class MyEmitter extends EventEmitter {} const myEmitter = new MyEmitter(); myEmitter.on('event', function() { console.log('an event occurred!'); }); myEmitter.emit('event');
在下面的例子,定义了一个名为Polygon的类,而后定义了一个继承于Polygon的类 Square。注意到在构造器使用的 super(),supper()只能在构造器中使用,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'; } }
使用关键字后就不用婆婆妈妈各类设置原型了,关键字已经封装好了,很快捷方便。