Home > Software engineering >  Accessing properties of "this" during bind
Accessing properties of "this" during bind

Time:01-17

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). However when this runs the from parameter to sendMail is always received as undefined.

If I replace sendMail: sendMail.bind(this, this.role) with sendMail: sendMail.bind(this, 'admin') it works fine.

How do I get the sendMail binding inside the admin object to pass variables defined inside the 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`);

CodePudding user response:

To do what you want, you'll have to separate out the assignment to the "sendMail" property:

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. While that's being evaluated, there is no object yet (at least conceptually).

  • Related