节点类中的Memoizee实例方法
我正在寻找一个优雅的方式来使用Memoizee包来记忆一个类的function。
在课堂之外,你可以轻松地做这件事:
const memoize = require('memoizee') const myFunc = memoize(function myfunc(){ ... })
但在一个类块里面,这是行不通的:
class foo { constructor(){ ... } // Without memoization you would do: myFunc(){ ... } // Can't do this here: myFunc = memoize(function myfunc(){ ... }) }
我可以想到使用this.
在构造函数中创build它this.
语法,但是这会导致不太一致的类定义,因为非memoized方法将在构造函数之外声明:
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));
1 = 0.6701435727286942 1 = 0.6701435727286942 2 = 0.38438568145894747 2 = 0.38438568145894747
根据你运行代码的方式以及你是否使用了转译步骤,也许你可以使用memoized-class-decorator :
class foo { constructor () { ... } // Without memoization: myFunc () { ... } // With memoization: @memoize myFunc () { ... } }
在memoizee中有专门的处理方法。 请参阅: https : //github.com/medikoo/memoizee#memoizing-methods
仍然不会使用本地类的语法,最好你可以在这一点上做的是:
const memoizeMethods = require('memoizee/methods'); class Foo { // .. non memoized definitions } Object.defineProperties(Foo.prototype, memoizeMethods({ // Memoized definitions, need to be provided via descriptors. // To make it less verbose you can use packages as 'd': // https://www.npmjs.com/package/d myFunc: { configurable: true, writable: true, enumerable: false, value: function () { ... } } });