Home > Net >  JavaScript .bind mehtod doesn't catch up a context
JavaScript .bind mehtod doesn't catch up a context

Time:10-13

In sendTo method of user I tried to bind earlier defined function and send this.name as the first argument. But if i try console logging, this.name returns undefind. How to correctcly bind context of user's object to sendTo() mehtod?

function sendFrom(from, to, text) {
    console.log(this);
    return `${from}'s packet --> ${to}  \nmessage: ${text}`;
}

let user = {
    name: "Alex",
    sendTo: sendFrom.bind(this, this.name),
}


user.sendTo = user.sendTo.bind(user);

console.log(user.sendTo("John", "some message"));
{}
undefined's packet --> John  
message: some message

CodePudding user response:

To undersand why this does not work you have to look at the user object:

sendTo: sendFrom.bind(this, this.name),

This property inside user is what is causing the issue. When this code is run this belongs to the window object and not the user.

So finally sendTo is a method with context as window and first param as window.name

That is why console.log(this) returns the window object.

When you do this: console.log(user.sendTo("John", "some message"));

You are adding the params "John" and "some message" after the already appended param.

So finally params become:

from, to, text -> window.name(undefined in your case), John, some message

Anytime you are using this in this code it is referring to window. There is actually no way to understand binding here and this example is not where you should be using bind

CodePudding user response:

I guess you can achieve expected behavior by not using any bindings:

function sendFrom(to, text) {
    console.log(this);
    return `${this.name}'s packet --> ${to}  \nmessage: ${text}`;
}

let user = {
    name: "Alex",
    sendTo: sendFrom
}

console.log(user.sendTo("John", "some message"));

But if you want to execute the user's method somewhere else that when binding comes into play:

let alexeSendTo = user.sendTo
alexesSendTo('John', 'Hey John!') // it will loose Alex's user context link

let alexeSendTo = user.sendTo.bind(user)
alexesSendTo('John', 'Hey John!') // now it is marked as Alex message
  • Related