- 多态实现及其应用
function extend(Child, Parent) {
Child.prototype = Object.create(Parent.prototype)
Child.prototype.constructor = Child
}
function Shape(color) {
this.color = color
}
Shape.prototype.duplicate = function() {
console.log('duplicate')
}
function Circle(radius, color) {
Shape.call(this, color)
this.radius = radius
}
extend(Circle, Shape)
Circle.prototype.draw = function() {
console.log('draw')
}
Circle.prototype.duplicate = function() {
console.log('circle duplicate')
}
function Square() {
}
extend(Square, Shape)
Square.prototype.duplicate = function() {
console.log('square duplicate')
}
const s = new Shape()
const c = new Circle(1, 'red')
const shapes = [
new Circle(),
new Square()
]
for (const shape of shapes) {
shape.duplicate()
}