我正在寻找一种优雅的方法来使用回忆录包回忆录类函数。
在课堂之外,你可以做一些琐碎的事情:
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.语法在构造函数中创建它,但这将导致类定义的不统一,因为非回忆录方法将在构造函数之外声明:
class foo {
constructor(){
// Inside for memoized:
this.myFunc = memoize(function myfunc(){ ... })
}
// Outside for non-memoized:
otherFunc(){ ... }
}如何包装实例方法?
发布于 2017-09-19 16:19:27
可以在构造函数中覆盖自己的方法定义
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发布于 2017-02-07 13:34:52
根据您运行代码的方式以及是否使用转移溢出步骤,也许您可以在以下情况下使用回忆录-阶级装饰师:
class foo {
constructor () { ... }
// Without memoization:
myFunc () { ... }
// With memoization:
@memoize
myFunc () { ... }
}发布于 2017-02-09 08:05:59
回忆录中有专门处理方法的方法。请参阅: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 () { ... }
}
});https://stackoverflow.com/questions/42089268
复制相似问题