57 - JavaScript 中的缓存 & 58 - JavaScript 中的多态

64 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第14天,点击查看活动详情

原文地址:dev.to/bhagatparwi…

JavaScript和函数式编程携手并进。有些时候,我们的功能将会付出高昂的性能代价。一直执行同样的函数接受同样的参数会降低应用的性能并且这也没有比较。

缓存是一种优化技术,用来保存我们函数返回的结果。如果我们向同一个函数输入相同的参数,我们就可以从缓存中获取结果而不是从执行代码获取,那样会导致性能问题。

万一结果没有被命中,我们将会执行函数且缓存结果。让我们以计算一个数的平方为例:

const square = () => {
    let cache = {}; // set cache
    return (value) => {
        // if exists in cache return from cache
        if (value in cache) {
            console.log("Fetching from cache");
            return cache[value];
        } else {
            // If not in cache perform operation
            console.log("Performing expensive query");
            const result = value * value;
            cache[value] = result; // store the value in cache
            return result; // return result
        }
    }
}

const sq = square();
console.log(sq(21)); // Performing expensive query, 441
console.log(sq(21)); // Fetching from cache, 441

为什么以及何时使用它?

  • 用于耗时的函数调用,例如:一个函数调用了网络且返回结果不会改变或需要大量计算的函数或硬盘读写。
  • 用于纯函数(同样的输入相同的输出)。
  • 用于有限的输入但值高度重复的函数调用。

58 - JavaScript 中的多态

原文地址:dev.to/bhagatparwi…

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

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

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 类型的不同做了改动。