再重温下之前继承的实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| var inherits = function(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; function Point(x, y) { this.x = x; this.y = y; } Point.prototype.toString = function() { return '(' + this.x + ', ' + this.y + ')'; } function ColorPoint(x, y, color) { Point.call(this, x, y); this.color = color; } inherits(ColorPoint, Point); ColorPoint.prototype.toString = function() { return this.color + ' ' + ColorPoint.super_.prototype.toString.call(this); }
|
然而es6则可以这么写
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| class Point { constructor(x, y) { this.x = x; this.y = y; } toString() { return '(' + this.x + ', ' + this.y + ')'; } } class ColorPoint extends Point { constructor(x, y, color) { super(x, y); this.color = color; } toString() { return this.color + ' ' + super.toString(); } }
|
显然es6的写法更加清晰,隐去了Javascript硬去使用prototype和call的实现细节。但是es6并没有完全按照Java ,C++面向对象的语法来实现,
只是对于原型继承的一个语法糖。