ES6でファクトリ関数をエクスポートしています。これは、プロパティを持つオブジェクトを返します。ファクトリを呼び出すと、オブジェクトが作成されますが、その値は更新されません。
例:
// factory.js
let counter = 1;
let factory = () => {
let increment = function(){
counter++;
}
return { counter, increment };
}
export default factory;
// main.js
import factory from './factory';
let f = factory();
console.log(f.counter); // =>1
f.increment();
console.log(f.counter); // => stil 1, not 2?
誰かがこれが起こっている理由を説明できますか?それはES6の機能ですか、それともwebpackとbabel(es2015-preset)を使用しているという事実と関係がありますか?
私はこれを見つけましたが、それは同じユースケースを説明していません:http://exploringjs.com/es6/ch_modules.html#sec_imports-as-views-on-exports
JavaScriptでは、プリミティブ型は値によって渡されます。
let counter = 1;
let factory = () => {
...
// The property `counter` in this object gets passed a value of the `counter` declared in the scope of `factory.js`.
// It does not get a reference.
return { counter, increment };
}
あなたがからオブジェクトを返すときにfactory
機能、そのプロパティがcounter
割り当てられている値をからcounter
のスコープで宣言しましたfactory.js
。これは、本質的に意味counter
オブジェクトのプロパティは、受信したコピーの値リンクは何もありません-値のをcounter
変数とcounter
プロパティが。
let counter = 1;
let factory = () => {
let increment = function () {
// The `++` operates on the `counter` variable declared in the scope of `factory.js`.
// There is no link between the value `counter` in the scope of `factory.js` and the `counter` as the property of the object returned.
// As a result when the `counter` variable is incremented, the `counter` property remains the same as the value initially passed to it.
counter++;
};
};
あなたがインクリメントするとcounter
、あなたはのスコープで宣言された変数の値をインクリメントしていますfactory.js
。変数の値があるNumber
ため、原始的です。プリミティブ値は値によって渡されるため、変数counter
とプロパティの間にリンクはありませんcounter
。
うまくいけば、すべてのことは、理にかなっています。あなたには、いくつかのより多くのこの考え方に読んでくださいしたい場合は値渡し(に比べて参照渡し)は、次のStackOverflowの質問を見ることができます:
この時点で、どうすればこれを修正できますか?
代わりに、インクリメントのcounter
あなたをインクリメントする必要がありますthis.counter
。このような:
let increment = () => {
this.counter++;
};
コンテキストはので、これは動作しますthis
関数から返されるオブジェクトですfactory
。counter
プロパティを使用すると、呼び出しの結果を割り当てた変数にありますfactory
。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加