一、原型的继承
function superType(name){
this.name = name;
}
superType.prototype.sayName = function(){
console.log(this.name)
}
function subType(name,age){
// 继承属性
superType.call(this,name);
this.age = age;
}
// 继承方法
subType.prototype = new superType();
subType.prototype.sayAge = function(){
console.log(this.age)
}
// subType 实例 同时拥有 name,age属性,sayName sayAge方法
var Alias = new subType("Alias",18)
Alias.sayName(); // "Alias"
Alias.sayAge() // 18
}
二、class 的继承
class SuperType {
// constructor
constructor(name){
this.name = name;
}
// getter
get city(){
return "ShangHai"
}
// Methods
sayName(){
console.log(this.name)
}
}
class SubType extends SuperType{
constructor(name,age){
// 继承属性
super(name);
this.age = age;
}
sayAge(){
console.log(this.age);
}
}