是否有在保留对象的同时解构对象属性的快捷方式?
Is there a shortcut to destructure an object properties while keeping the object?
如果我有如下方法签名:
const myFunction = ({ property1, property2, property3 }) => ...
有没有办法也可以抓取父对象?否则我必须这样写:
const myFunction = myObject => {
const { property1, property2, property3 } = myObject
}
如果您愿意使用传统函数而不是箭头函数,您可以使用 arguments
对象来获取:
function test({a, b}) {
console.log(a);
console.log(b);
console.log(arguments[0]);
}
test({
a: 'This is a',
b: 'This is b',
});
(你不能在箭头函数中这样做,因为箭头函数没有自己的 arguments
绑定,它们会关闭周围上下文中的那个,就像它们 this
和[相关] super
.)
在下面的示例中,您可以通过解构访问 x
& y
属性和 cords
本身:
const drawCircle = ({cords, cords: {x,y},radius}) =>
console.log(cords, x, y, radius)
const circle = {
cords: {
x: 18,
y: 30
},
radius: 50
}
drawCircle(circle)
它有点笨拙,但您可以通过以下方式调用函数来获取整个对象:
drawCircle({circle})
并像这样解构对象:
({circle, circle: {cords, cords: {x, y}, radius}})
如果我有如下方法签名:
const myFunction = ({ property1, property2, property3 }) => ...
有没有办法也可以抓取父对象?否则我必须这样写:
const myFunction = myObject => {
const { property1, property2, property3 } = myObject
}
如果您愿意使用传统函数而不是箭头函数,您可以使用 arguments
对象来获取:
function test({a, b}) {
console.log(a);
console.log(b);
console.log(arguments[0]);
}
test({
a: 'This is a',
b: 'This is b',
});
(你不能在箭头函数中这样做,因为箭头函数没有自己的 arguments
绑定,它们会关闭周围上下文中的那个,就像它们 this
和[相关] super
.)
在下面的示例中,您可以通过解构访问 x
& y
属性和 cords
本身:
const drawCircle = ({cords, cords: {x,y},radius}) =>
console.log(cords, x, y, radius)
const circle = {
cords: {
x: 18,
y: 30
},
radius: 50
}
drawCircle(circle)
它有点笨拙,但您可以通过以下方式调用函数来获取整个对象:
drawCircle({circle})
并像这样解构对象:
({circle, circle: {cords, cords: {x, y}, radius}})