我想知道 ES6 是否可以实现以下操作。
我有一个对象“o”,其方法为:
get(name) {
}
根据提供的名称返回一些其他对象。
我有另一个这样的功能测试:
function test(o) {
}
我想知道是否有任何方法可以通过调用对象的 get 来解构参数。
例如:这不起作用 - 这是我想做的事情
// here is what I'm trying to do
function test({db: get('db')}) {
}
// this is working
function test(o) {
var db = o.get('db');
}
我希望“db”变量等于“o.get('db')”。我可以在函数体中执行此操作,但我想知道是否可以在参数定义中直接执行它。
到目前为止我可以使用:
let [a, b, c] = [o.get('a'), o.get('b'), o.get('c')];
作为函数中的第一行。
谢谢
最佳答案
您可以使用 getter 代替通用的 get
函数。这将允许解压并使其余代码更易于阅读:
let SomeObj = {
get db() {
return "this is db";
}
}
function func({db}) {
console.log('DB', db);
}
func(SomeObj);
如果你的属性是动态的,你可能会做这样可怕的事情:
let SomeObj = {
get(name) {
return `this is ${name}`;
}
}
function func(o, {db = o.get('db'), blah = o.get('blah')} = {}) {
console.log('DB', db);
console.log('blah', blah);
}
func(SomeObj);
但更现实的选择是拥有一个将 get
映射到 props 数组的函数:
let SomeObj = {
get(name) {
return `this is ${name}`;
}
}
let extract = (obj, ...props) => props.map(p => obj.get(p));
function func(o) {
let [db, blah] = extract(o, 'db', 'blah')
console.log('DB', db);
console.log('blah', blah);
}
func(SomeObj);
最后,您可以将对象包装在 Proxy
中以提供动态 getter,在这种情况下,简单的解构将立即可用:
let SomeObj = new Proxy({}, {
get(obj, name) {
if(name in obj)
return obj[name];
return `this is ${name}`;
}
});
function func({db, blah}) {
console.log('DB', db);
console.log('blah', blah);
}
func(SomeObj);
关于javascript - 使用动态对象属性进行 ES6 解构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58233037/