実際のコードはより大きいので、投稿しません。問題無限ループで配列関数を再利用する方法
class A {
process(source) {
// I perform several operations with array helper functions here:
const filtered = source.filter(item => item);
const condition = filtered.some(item => item);
if (condition) {
const mapped = source.map(item => /* Mapping operations... */);
const sorted = mapped.sort((a, b) => { /* Some sort conditions... */ });
return sorted;
} else {
const mapped2 = filtered.map(item => /* A different mapping operation... */);
return mapped2;
}
}
}
const a = new A();
while (true) {
const source = getSourceFromSomewhere(); // Array (40 - 50 items aprox)
const b = a.process(source);
// ...
}
:これはかなりこのようになります基本的には、パフォーマンス。 "ループ内で関数を作成しない"。
すべての反復で、一連の匿名関数が作成されています。
私のソリューション:
class A {
// Predefine it:
sort() { /* Sort logic */ }
map() { /* Map logic */ }
map2() { /* Map logic */ }
filter() { /* Filter logic */ }
some() { /* Condition */ }
process(source) {
const filtered = source.filter(this.filter); // Note: Scope of 'this' is changed.
const condition = filtered.some(this.some);
if (condition) {
const mapped = source.map(this.map);
const sorted = mapped.sort(this.sort);
return sorted;
} else {
const mapped2 = filtered.map(this.map2);
return mapped2;
}
}
}
もう一つの問題:この機能の一部は、オブジェクト自体のプロパティにアクセスする必要がありますが、
this
の範囲が変更されました。
匿名機能を作成する代わりに.bind(this)
を呼び出すのは価値がありますか?またはほぼ同じですか?
私の場合はどうしますか?
ありがとうございます。あなたはとにかくやりたいこと
class Test {
fn = (t) => this[t]
}
は基本的に同じ行うことができ、クラス内に結合機能を初期化するために
これはどのように動作するはずです。 'fn'はどこで呼び出されますか? 'fn( 'foo')は' this.foo'とどう違うのですか?クラスの 'this'の代わりに、' fn'の中の 'this'が周囲の' this'ではありませんか? –