【发布时间】:2020-06-02 15:59:58
【问题描述】:
考虑以下脚本:
let object = {
text1: 'this is text1',
text2: 'this is text2'
}
class Translate {
constructor() {
this.localization = null;
this.lateForTheShow = [];
init();
}
async init() {
/** Perform an ajax call to fetch a localization file **/
this.localization = await ajaxCall(...);
for (let i in this.lateForTheShow) {
this.translate(this.lateForTheShow[i].originalText, this.lateForTheShow[i].referencedVariable);
}
}
translate(text, &pointer) {
if (this.localization === null) {
this.lateForTheShow.push({
referencedVariable: pointer,
originalText: text
});
} else {
text = this.localization[text];
}
pointer = text;
}
}
let TranslateObj = new Translate();
TranslateObj.translate(object.text1, object.text1);
上面的代码不是一个有效的javascript代码,因为你不能在javascript中传递指向变量的指针(至少肯定不是PHP我传递它们的方式)。不过,可以在PHP 中完成类似的事情,我想知道是否可以在 javascript 中实现类似的事情?
【问题讨论】:
-
“一个常见但不正确的解释是 JavaScript 中传递数字和数组的语义不同。有人声称数字是按值传递的,而数组是按引用传递的。相反,它更准确地说,数组和数字 [和对象] 都是通过共享传递的。虽然数组是可变的,但数字不是。” - 这句话有帮助吗? ([] - 由我添加)
-
@evolutionxbox 不是真的,不:P 也许我在工作 8 小时后很累,但这并没有让我更接近我想去的地方:)
-
你提到了指针。 AFAIK JavaScript 不是真的没有它们吗? wafy.me/tech/2016/07/02/call-by-sharing.html
-
如果您将
this.lateForTheShow设置为一个空数组,然后调用init并在其中有一个循环,那么您希望循环体如何执行? -
@trincot 因为
init函数是async函数,所以this.lateForTheShow很可能会被填充,当代码到达for loop时。还是我在这里弄错了?
标签: javascript