猿问

如何在外部变量更改时更新对象属性

我再次偶然发现了我不理解的 Javascript 行为。一旦对象外部的变量发生更改,我就需要更新对象的属性。外部变量在对象属性中被引用,所以我认为我所要做的就是从外部更改变量并自动更改属性值。


这是代码外观的简化版本:


var serverPath = "123/";


var GetCurrentProductionApiConfig = {

  URL: {

    GetStart: serverPath + 'GetCurrentProduction?returnValue=start&',

    GetEnd: serverPath + 'GetCurrentProduction?returnValue=end&',

    Get: serverPath + 'GetCurrentProduction?returnValue=start&'

  }

};


serverPath = "456/";


console.log(GetCurrentProductionApiConfig.URL.GetStart);

这将导致:


123/GetCurrentProduction?returnValue=start&


是因为变量已被复制(通过值传递)而不是在其上有一个指针(通过引用传递)?哪种方式是更新属性的正确方式?


哆啦的时光机
浏览 121回答 1
1回答

至尊宝的传说

JavaScript 中的所有内容都是按值传递的,但碰巧对象的值是它的引用。然而,这里重要的是对于原语,当引用的变量发生变化时不会发生变化:var a = "world";var obj = {  b: "hello" + a //evaluated once}a = "universe"; //does not modify obj.b which references aconsole.log(obj.b); //helloworld为了获得动态计算的字符串,您需要调用一个函数或方法:var a = "world";var obj = {  b: function() {     return "hello" + a //evaluated every time the function is executed  }}console.log(obj.b()); //helloworlda = "universe"; //will influence obj.bconsole.log(obj.b()); //hellouniverse然而,这看起来有点“脏”,因为它迫使调用者知道每次都评估属性。如果某些属性是纯字符串,而其他属性是函数,则它还会引入不一致,如果属性必须从一个更改为另一个,则尤其烦人 - 您需要修改调用此代码的每个位置以更改,例如更改obj.c为obj.c().相反,使用 ES6+,您可以为属性定义一个 getter,该属性将执行与以前相同的操作,但会隐藏函数调用,因此无论何时您读取一个属性,您实际上都会评估代码以返回结果:var a = "world";var obj = {  c: "plain property"}Object.defineProperty(obj, 'b', {  get: function() {    return "hello" + a //evaluated every time the property is read  }});console.log(obj.b); //helloworlda = "universe"; //will influence obj.bconsole.log(obj.b); //hellouniverseconsole.log(obj.c); //plain property
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答