我有一个类,我想从用户提供的文件内容中构造它。
当我创建一个FileReader对象并向其添加onload函数时,我不能用this
关键字调用类字段或方法。
所以我有这个类和函数:
class Dictionary {
constructor(words) {
...
this.words = words;
...
}
...
}
function createDictionaryFromFile(file) {
let reader = new FileReader();
reader.onload = function() {
dictionary = new Dictionary(reader.result);
}
reader.readAsText(file);
}
但我不想在类之外有字典对象创建函数(我想隐藏createDictionaryFromFile函数,最好在dictionary类中(
如何处理这个问题?
只是另一个例子:
class Dictionary {
constructor(words) {
this.words = words
}
static fromBlobLike(file) {
return file.text().then(t => new Dictionary(t))
}
}
Dictionary.fromBlobLike( new File(['abc'], 'hello.txt') ).then(console.log)
Dictionary.fromBlobLike( new Blob(['def']) ).then(console.log)
Dictionary.fromBlobLike( new Response(['ghi']) ).then(console.log)
但我认为Dictionary类不应该负责读取文件。如果你从洋葱架构的角度来看,那么核心组件应该只处理逻辑,然后第二层是os/web/nodeo/react,负责读取/写入并使网络调用
在JS的最新方言中,您可以使函数成为类的静态方法。看起来是这样的:
class Dictionary {
constructor(words) {
...
this.words = words;
...
}
static createFromFile(file) {
let reader = new FileReader();
reader.onload = function() {
dictionary = new Dictionary(reader.result);
}
reader.readAsText(file);
}
...
}
然后将其称为Dictionary.createFromFile(...)
。请注意,您实际上并不是从这个函数返回字典。要做到这一点,您需要一种异步方法,如promise或回调。