【问题标题】:Pass object property as a pointer in javascript [duplicate]在javascript中将对象属性作为指针传递[重复]
【发布时间】: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


【解决方案1】:

在 JavaScript 中对象是通过引用传递的,所以把它变成一个对象并且你有一个指针。

【讨论】:

    【解决方案2】:

    在 JavaScript 中,对象默认通过引用传递。只有某些类型,如字符串、数字等,是按值传递的。

    示例:按值传递

    function myFunction(arg0 /*arg0 is the copied variable */) {
      arg0 += 10;
      console.log(aVar); //displays 15
    } //goodbye arg0…
    
    var aVar = 5;
    console.log(aVar); //displays 5
    myFunction(aVar);
    console.log(aVar); //still displays 5
    

    示例:通过引用传递

    function myFunction(arg0) {
      arg0 = "I'm still a string!";
      console.log(arg0); //displays "I'm still a string!"
    }
    
    var aVar = {val: "I'm a string!"};
    console.log(aVar.val); //displays "I'm an object!"
    myFunction(aVar.val);
    console.log(aVar.val); //displays "I'm a string!"
    

    对您的问题的简短回答是,没有办法传递我所知道的指针,但您可以通过玩对象来实现类似的行为。在某些情况下,JS 可能会出现混乱的语言。

    参考资料:

    代码示例取自https://www.htmlgoodies.com/html5/javascript/passing-javascript-function-arguments-by-reference.html

    还有一个更好的解释它是如何在 JavaScript 中工作的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-25
      • 2017-01-19
      • 1970-01-01
      • 1970-01-01
      • 2021-04-18
      • 1970-01-01
      • 2013-03-16
      相关资源
      最近更新 更多