2 回答

TA貢獻1836條經驗 獲得超4個贊
您可以使用with語法,但不推薦這樣做,因為
不推薦使用 with 語句,因為它可能會導致令人困惑的錯誤和兼容性問題。
const foo = {
data: {
user: {
name: 'Alice',
age: 18
}
}
};
with(foo.data.user) {
name = 'Bob';
age = 24;
}
console.log(foo);

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 是有意義的。
添加回答
舉報