-
实例化:A类依赖于B类。
class B { doSth () { } } class A { constructor () {} run () { const b = new B() b.doSth() } } new A().run()
-
委托:A对象依赖于B对象。
class B { doSth () { } } const b = new B() class A { constructor () {} run () { b.doSth() } } new A().run()
-
聚合:A对象和B对象是"has-a"关系。
class Student { constructor(name) { this.name = name } } class Classroom { constructor() { this.students = [] } addStudent(student) { this.students.push(student) } } let student1 = new Student('Alice') let student2 = new Student('Bob') let classroom = new Classroom() classroom.addStudent(student1) classroom.addStudent(student2)
-
组合:A对象和B对象是"is-a"关系。
class Creature { constructor(name) { this.name = name } } class Eye { constructor(color) { this.color = color } } class Human extends Creature { constructor() { super('Human') this.leftEye = new Eye('blue') this.rightEye = new Eye('brown') } }
-
继承:A类和B类是"is-a"关系。