全部 / 前端 / 技术 · 2022年7月10日 0

58 – JavaScript 中的多态

原文地址:https://dev.to/bhagatparwinder/polymorphism-in-javascript-1960

多态是面向对象中的一个概念,它是可以通过多种方法实现一个属性、方法或对象的能力。

它允许我们在具有共同功能的类中替代属性或方法,有点类似方法重写。在多态的帮助下,我们可以实现一个标准的接口同时满足稍微的差异或不同的场景。

function Employee(name) {
    this.name = name;
    this.getName = () => {
        return this.name;
    }
}

const employee = new Employee("Parwinder");

console.log(employee.getName()); // Parwinder

Employee.prototype.getDetails = function () {
    return this.name.toUpperCase();
}

console.log(employee.getDetails()); // PARWINDER

从上面你可以看出 Employee 如何根据我们使用它的实例的位置来实现一个标准的接口,同时能进行行为上稍微的改动来满足需求。我们不仅可以获取名字还能获取名字的大写形式。

我们同样可以使用类来达到相同的目的:

class Shape {
    area() {
        return 0;
    }
}

class Circle extends Shape {
    constructor (radius) {
        super(); // needed to use this
        this.radius = radius;
    }

    area() {
        return Math.PI * this.radius * this.radius;
    }
}

class Rectangle extends Shape {
    constructor (width, height) {
        super();
        this.width = width;
        this.height = height;
    }

    area() {
        return this.width * this.height;
    }
}

const circle = new Circle(2);
const rectangle = new Rectangle(5, 6);

console.log(circle.area());
console.log(rectangle.area());

Shape 是我们创建 Circle 和 Rectangle 的基类。它们都有 area 方法但是根据 shape 类型的不同做了改动。