如何通过引用复制对象属性

physicsObjects.forEach(obj => {

  let coor = obj.coordinates;

  let vel = obj.velocity;

  obj.coordinates = addVectors(coor, [0.1, 0.1]);

})

这得到参考。


physicsObjects.forEach(obj => {

  let coor = obj.coordinates;

  let vel = obj.velocity;

  coor = addVectors(coor, [0.1, 0.1]); 

})

这只会改变“coor”。我试过创建一个临时对象,并用临时对象替换原始对象,但这不是直接的方法。


如何通过引用访问对象属性?除了像第一个例子那样直接访问它,我的意思是。我现在才需要这个,这样做object.property.property.property = someValue;会很痛苦。是否有一个 javascript 等效于:


var *objectProperty = &someobject.someproperty;


守候你守候我
浏览 124回答 2
2回答

HUH函数

您可以使用with语法,但不推荐这样做,因为不推荐使用 with 语句,因为它可能会导致令人困惑的错误和兼容性问题。const foo = {  data: {    user: {      name: 'Alice',      age: 18    }  }};with(foo.data.user) {  name = 'Bob';  age = 24;}console.log(foo);

MMMHUHU

也许 JavaScript 中更惯用的方法是使用this和作用域:function addVectors(vector) {  // Use only the *second* argument, like [0.1, 0.1], not 'coor')    let newCoordinates = /* do same calculations as you did */    // Instead of *return newCoordinates;* at the end:     this.coordinates = newCoordinates;}// Approach 1:// Now "bind" the function inside the object, so that "this" refers to it. let objExample = {   velocity: 42,   coordinates: [1.2, 3.4],   add: addVectors,}// use it like this (in your foreach for instance):objExemple.add([0.1, 0.1]);// Approach 2:// Use 'call' to bind the 'this' parameter to the object dynamically// (directly in your foreach without any more changes)addVectors.call(obj, [0.1, 0.1]); 对于您给出的示例,我会选择方法 2,需要的代码更少。如果您在不同的地方重复使用这个“addVectors”函数,那么选择方法 1 是有意义的。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript