类继承增加了一条父子链,子类继承了超类,函数继承中子类继承Function原型。
//类继承
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 super.toString + ' in ' + this.color;
}
}
log(ColorPoint.prototype.__proto__ === Point.prototype)//true
log(ColorPoint.__proto__ === Point);//true
log(ColorPoint.__proto__ === Function.prototype);//false
log(Point.__proto__ === Function.prototype);//true
//函数继承
function Clock (timezone) {
this.timezone = timezone;
}
Clock.prototype.greeting = function () {
console.log('A clock - ' + this.timezone);
}
function PrettyClock (timezone, color) {
Clock.call(this, timezone);
this.color = color;
}
PrettyClock.prototype = Object.create(Clock.prototype);
PrettyClock.prototype.constructor = PrettyClock;
PrettyClock.prototype.greeting = function () {
console.log('A clock - ' + this.timezone + ' + ' + this.color);
}
log(PrettyClock.prototype.__proto__ === Clock.prototype)//true
log(PrettyClock.__proto__ === Clock);//false
log(PrettyClock.__proto__ === Function.prototype);//true
log(Clock.__proto__ === Function.prototype);//true