A 对象通过继承 B 对象,就能直接拥有 B 对象的所有属性和方法。
1. 基于原型继承
//父类
function Shape(){
this.x = 0
this.y = 0
}
//父类的方法
Shape.prototype.move = function(x, y){
this.x += x
this.y += y
console.log('Shape moved')
}
//子类
function Rectangle(){
Shape.call(this)
}
//子类继承父类
Rectangle.prototype = Object.create(Shape.prototype)
Rectangle.prototype.constructor = Rectangle
const rect = new Rectangle()
console.log(rect instanceof Rectangle) //true
console.log(rect instanceof Shape) //true
rect.hasOwnProperty('move') //false
rect.move(1, 1) //Shape moved
如果希望能继承到多个对象(多重继承),可以使用混入的方式
function B1(){
this.x = 1
}
B1.prototype.hello = 'hello'
function B2(){
this.y = 2
}
B2.prototype.world = 'world'
function A(){
B1.call(this)
B2.call(this)
}
//继承B1
A.prototype = Object.create(B1.prototype)
//加入B2
Object.assign(A.prototype, B2.prototype)
A.prototype.constructor = A
const a = new A()
a.x //1
a.y //2
a.hello //hello
a.world //world
2. 基于 class 的继承
//父类
class Person{
constructor(name, age){
this.name = name
this.age = age
}
showName(){
console.log(this.name, this.age)
}
}
//子类
class Student extends Person{
constructor(name, age, major){
//通过super调用父类的方法
super(name, age)
this.major = major
}
showName(){
console.log(this.name, this.age, this.major)
}
}
const p1 = new Person('小红', 18)
const s1 = new Student('小明', 19, 'Chemistry')
p1.showName //小红 18
p2.showName //小明 19 Chemistry