简体   繁体   English

在绑定期间访问“this”的属性

[英]Accessing properties of "this" during bind

Learning partial functions and got stuck with this query -学习部分功能并陷入这个查询 -

In the code snippet below, I create an admin object that re-uses a generic sendMail function by customizing it with a bind (partial function).在下面的代码片段中,我创建了一个管理员 object,它通过使用绑定(部分功能)对其进行自定义来重新使用通用的 sendMail function。 However when this runs the from parameter to sendMail is always received as undefined .但是,当此运行from参数到sendMail时,始终接收为undefined

If I replace sendMail: sendMail.bind(this, this.role) with sendMail: sendMail.bind(this, 'admin') it works fine.如果我将sendMail: sendMail.bind(this, this.role)替换为sendMail: sendMail.bind(this, 'admin')它工作正常。

How do I get the sendMail binding inside the admin object to pass variables defined inside the admin object?如何让admin sendMail中的 sendMail 绑定传递在admin object 中定义的变量?

function sendMail(from, to, content) {
    console.log(`Sending email from ${from} to ${to} with message as ${content}`);
}

let admin = {
    role: `admin`,
    sendMail: sendMail.bind(this, this.role),
}
admin.sendMail(`all`, `Reboot in 15 mins`);

To do what you want, you'll have to separate out the assignment to the "sendMail" property:要做你想做的事,你必须将分配给“sendMail”属性分开:

let admin = {
    role: `admin`,
};
admin.sendMail = sendMail.bind(admin, admin.role);

There's no way to reference the "under construction" object in the property value expressions in an object initializer.无法在 object 初始值设定项的属性值表达式中引用“正在建设中”的 object。 While that's being evaluated, there is no object yet (at least conceptually).虽然正在评估,但还没有 object (至少在概念上)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM