为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

哆啦的时光机 2021-10-21 13:37:53
我再次偶然发现了我不理解的 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&是因为变量已被复制(通过值传递)而不是在其上有一个指针(通过引用传递)?哪种方式是更新属性的正确方式?
查看完整描述

1 回答

?
至尊宝的传说

TA贡献1789条经验 获得超10个赞

JavaScript 中的所有内容都是按值传递的,但碰巧对象的值是它的引用。然而,这里重要的是对于原语,当引用的变量发生变化时不会发生变化:


var a = "world";

var obj = {

  b: "hello" + a //evaluated once

}


a = "universe"; //does not modify obj.b which references a


console.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()); //helloworld


a = "universe"; //will influence obj.b


console.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); //helloworld


a = "universe"; //will influence obj.b


console.log(obj.b); //hellouniverse

console.log(obj.c); //plain property


查看完整回答
反对 回复 2021-10-21
  • 1 回答
  • 0 关注
  • 120 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信