我想知道ES6是否可以进行以下操作。
我有一个对象“ o”,使用方法:
get(name) {
}
根据提供的名称返回其他对象。
我有另一个类似的功能测试:
function test(o) {
}
我想知道有什么方法可以通过在对象上进行call来破坏参数。
例如:这不起作用-这是我想做的事情]
// 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')];
作为函数的第一行。
感谢
您可以使用吸气剂代替通用的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
的函数:
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);