亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何通過引用復制對象屬性

如何通過引用復制對象屬性

守候你守候我 2022-11-27 17:15:31
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;
查看完整描述

2 回答

?
HUH函數

TA貢獻1836條經驗 獲得超4個贊

您可以使用with語法,但不推薦這樣做,因為


不推薦使用 with 語句,因為它可能會導致令人困惑的錯誤和兼容性問題。


const foo = {

  data: {

    user: {

      name: 'Alice',

      age: 18

    }

  }

};


with(foo.data.user) {

  name = 'Bob';

  age = 24;

}


console.log(foo);


查看完整回答
反對 回復 2022-11-27
?
MMMHUHU

TA貢獻1834條經驗 獲得超8個贊

也許 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 是有意義的。


查看完整回答
反對 回復 2022-11-27
  • 2 回答
  • 0 關注
  • 115 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號