我在模块 A 中定义了一个数组,并希望通过模块 B 将其公开
模块 A 的启动方式如下:
define(["require", "exports"], function(require, exports) {
exports.flows = [];
模块 B 的启动方式如下:
define(["require", "exports", 'A/A'], function(require, exports, A) {
exports.flows = A.flows;
当修改模块 B 中的数组时,显然也会在模块 A 中修改数组。如下所示:
//in module B
exports.flows.push(1);
exports.flows.length //1
A.flows.length //1
但是当我像这样重置(清空)模块 A 中的数组时:
//in module A
exports.flows = [];
那么模块A和模块B中的数组将不再相同:
//in module B
exports.flows.length //1
A.flows.length //0
为什么?
谢谢
最佳答案
Why?
因为做
export.flows = [];
...创建一个新数组并将其分配给export.flows
属性。这对引用旧数组的其他属性(或变量)没有任何影响。
这是一个更简单的示例:
var a = [];
var b = a; // `a` and `b` refer to the *same* array
a.push(1);
console.log(a.length); // 1
console.log(b.length); // 1, both `a` and `b` refer to the *same* array
a = []; // Now `a` refers to a different array, but `b` still
// refers to the previous one
console.log(a.length); // 0, because the new array is empty
console.log(b.length); // 1, because `b` doesn't refer to the same array as `a`
关于javascript - requirejs 导出的数组重置为 [] 文字不再导出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22519229/