Javascript 有人能给我解释一下:“create({email:emailArg}={}){}”?
我还在学习JS。执行阿波罗GraphQL教程: 我不太理解这部分:findOrCreateUser{email:emailArg}={} 完整代码如下:Javascript 有人能给我解释一下:“create({email:emailArg}={}){}”?,javascript,node.js,graphql,apollo,Javascript,Node.js,Graphql,Apollo,我还在学习JS。执行阿波罗GraphQL教程: 我不太理解这部分:findOrCreateUser{email:emailArg}={} 完整代码如下: /** * User can be called with an argument that includes email, but it doesn't * have to be. If the user is already on the context, it will use that user * instea
/**
* User can be called with an argument that includes email, but it doesn't
* have to be. If the user is already on the context, it will use that user
* instead
*/
async findOrCreateUser({ email: emailArg } = {}) {
const email =
this.context && this.context.user ? this.context.user.email : emailArg;
if (!email || !isEmail.validate(email)) return null;
const users = await this.store.users.findOrCreate({ where: { email } });
return users && users[0] ? users[0] : null;
}
async bookTrips({ launchIds }) {
const userId = this.context.user.id;
if (!userId) return;
let results = [];
// for each launch id, try to book the trip and add it to the results array
// if successful
for (const launchId of launchIds) {
const res = await this.bookTrip({ launchId });
if (res) results.push(res);
}
return results;
}
请教育我,否则可以链接到解释。谢谢
findOrCreateUser({ email: emailArg } = {})
是几个原则的结合
1对象分解
相当于:
const prop = obj.prop;
2函数参数分解
同样的事情,只是函数的参数
function fun({ prop }) {
console.log(prop);
}
相当于
function fun(obj) {
console.log(obj.prop);
}
function fun(obj) {
const newPropName = obj.prop;
console.log(newPropName);
}
3分解结构时重命名变量
相当于
function fun(obj) {
console.log(obj.prop);
}
function fun(obj) {
const newPropName = obj.prop;
console.log(newPropName);
}
4默认功能参数
结论:
相当于
findOrCreateUser(args) {
const emailArg = args ? args.email : {};
// [...]
}
换句话说,它将传递给方法的对象的email属性重命名为emailArg,并使其直接可用。如果没有向函数传递任何内容,它还会初始化空对象的参数。这是为了避免在未传递任何信息的情况下引发无法读取未定义的电子邮件
如果您需要更多上下文,以下是文档:
我认为:
1函数希望接收一个JavaScript对象作为其第一个参数,该对象内部有一个名为email的属性
2在函数中,我们将该电子邮件属性称为emailArg
最后,={}部分提供了一个空对象作为默认值,有助于避免错误
关于函数参数的解构的更详细的解释可以在这里找到:可能与来自MDN的重复:示例代码:那么,它基本上与findOrCreateUser{email:emailArg}类似?那么添加={}有什么意义呢?
findOrCreateUser({ email: emailArg } = {}) {
// [...]
}
findOrCreateUser(args) {
const emailArg = args ? args.email : {};
// [...]
}