
这个 enablecache 函数的核心在于:
为了将 enableCache 装饰器应用于类中的多个方法,我们可以创建一个 enableCacheOnMethods 函数,该函数接受一个类作为参数,并遍历类的原型对象上的所有方法,将 enableCache 装饰器应用于每个方法。
function enableCacheOnMethods(cls) {
    const obj = cls.prototype;
    for (const method of Object.getOwnPropertyNames(obj)) {
        if (typeof obj[method] === "function" && method !== "constructor") { // method of cls
            obj[method] = enableCache(obj[method]);
        }
    }
}这个 enableCacheOnMethods 函数的工作原理如下:
以下是一个完整的示例代码,演示了如何使用 enableCache 装饰器和 enableCacheOnMethods 函数来简化类中缓存属性的处理。
function enableCache(func) {
    const cache = {};
    return function(...args) {
        const key = JSON.stringify([this, ...args]);
        if (!cache[key]) {
            cache[key] = { value: func.apply(this, args) };
        }
        return cache[key].value;
    };
}
function enableCacheOnMethods(cls) {
    const obj = cls.prototype;
    for (const method of Object.getOwnPropertyNames(obj)) {
        if (typeof obj[method] === "function" && method !== "constructor") { // method of cls
            obj[method] = enableCache(obj[method]);
        }
    }
}
// Demo
class myClass {
    divisors(n) { // Example method (without caching)
        console.log(`executing divisors(${n})`);
        const arr = [];
        for (let i = 2; i <= n; i++) {
            if (n % i == 0) arr.push(i);
        }
        return arr;
    }
    factorial(n) { // Example method (without caching)
        console.log(`executing factorial(${n})`);
        let res = 1;
        while (n > 1) res *= n--;
        return res;
    }
}
enableCacheOnMethods(myClass);
let obj = new myClass;
console.log(...obj.divisors(15));
console.log(...obj.divisors(48));
console.log(obj.factorial(10));
console.log(...obj.divisors(15)); // Uses the cache
console.log(obj.factorial(10)); // Uses the cache在这个示例中,divisors 和 factorial 方法都被 enableCache 装饰器装饰,这意味着它们的结果会被缓存。当我们第一次调用这些方法时,它们会执行计算并将结果存储到缓存中。当我们再次调用这些方法时,它们会直接从缓存中返回结果,而不会再次执行计算。
立即学习“Java免费学习笔记(深入)”;
通过使用装饰器和对象包装,我们可以避免在每个方法中重复编写缓存逻辑,从而简化代码,提高代码的可读性和可维护性。同时,使用 ??= 运算符可以简化缓存逻辑,使其更加简洁高效。在实际应用中,我们需要根据具体情况选择合适的缓存键和缓存失效机制,并权衡缓存带来的性能提升和缓存带来的额外开销。
以上就是优化 JavaScript 类中缓存属性处理的实用技巧的详细内容,更多请关注php中文网其它相关文章!
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
                
                                
                                
                                
                                
                                
                                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号