如果您看下面的示例,您会发现我在启动时设置了全局值。之后,如果单击注入模块,您会看到我将对象的22
属性设置为tag_id
并具有新值。我不明白为什么要在另一个变量中设置全局对象将tag_id
的值更改为22
的原因。我不希望全球价值发生变化。
[{"id":"a1dc09e7.208b48","type":"function","z":"81ac975c.542c88","name":"","func":"var o = global.get(\"machine\");\nnode.warn(o[1]);\no[1].tag_id = 22;\n\n","outputs":1,"noerr":0,"x":350,"y":320,"wires":[[]]},{"id":"4cca337d.f22bfc","type":"inject","z":"81ac975c.542c88","name":"","topic":"","payload":"","payloadType":"date","repeat":"","crontab":"","once":false,"onceDelay":"5","x":140,"y":320,"wires":[["a1dc09e7.208b48"]]},{"id":"fd1f90c5.86b85","type":"inject","z":"81ac975c.542c88","name":"Startup","topic":"","payload":"","payloadType":"date","repeat":"","crontab":"","once":true,"x":140,"y":220,"wires":[["950e20e9.dd2d3"]]},{"id":"950e20e9.dd2d3","type":"function","z":"81ac975c.542c88","name":"","func":"msg ={\n\t\"1\": {\n\t\t\"timestamp\": \"\",\n\t\t\"tag\": \"\",\n\t\t\"tag_id\": 0,\n\t\t\"value\": 0,\n\t\t\"units\": \"\"\n\t}\n}\n\nglobal.set(\"machine\",msg);\n\n//return msg; ","outputs":1,"noerr":0,"x":350,"y":220,"wires":[[]]}]
答案 0 :(得分:2)
这是JavaScript通过引用而不是值传递对象的不良结果。当您从上下文中检索对象时,您将获得上下文中对该对象的引用。您所做的任何更新都会反映在上下文中。
如果要更改对象而不修改原始对象,则需要克隆它:
var o = RED.util.cloneMessage(global.get("machine"));