gpt4 book ai didi

javascript - Node 类中的Memoizee实例方法

转载 作者:搜寻专家 更新时间:2023-11-01 00:16:56 24 4
gpt4 key购买 nike

我正在寻找一种使用 Memoizee package 来内存类函数的优雅方法.

在类之外,你可以简单地做这件事:

const memoize = require('memoizee')

const myFunc = memoize(function myfunc(){ ... })

但是在类 block 中,这将不起作用:

class foo {
constructor(){ ... }

// Without memoization you would do:
myFunc(){ ... }

// Can't do this here:
myFunc = memoize(function myfunc(){ ... })
}

我可以考虑使用 this. 语法在构造函数中创建它,但这会导致类定义不太统一,因为非记忆化方法将在构造函数外部声明:

class foo {
constructor(){
// Inside for memoized:
this.myFunc = memoize(function myfunc(){ ... })
}

// Outside for non-memoized:
otherFunc(){ ... }
}

您将如何包装实例方法?

最佳答案

可以在构造函数中覆盖自己的方法定义

class Foo {
constructor() {
this.bar = _.memoize(this.bar);
}

bar(key) {
return `${key} = ${Math.random()}`;
}
}

const foo = new Foo();
console.log(foo.bar(1));
console.log(foo.bar(1));
console.log(foo.bar(2));
console.log(foo.bar(2));


// Output:
1 = 0.6701435727286942
1 = 0.6701435727286942
2 = 0.38438568145894747
2 = 0.38438568145894747

关于javascript - Node 类中的Memoizee实例方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42089268/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com