What the bind method with the solution of the problem?

Teach JS, come to the theme knows where the bind method.
Read the lecture, but virtually nothing is understood.
Namely how exactly is the loss of context? How to understand this? As I understand the loss and need to use bind.

Try to solve the presented tasks. Thought thought, but as he could not understand the lecture, then the problem is of course not able to solve.
Looked decision, but did not understand why you need to use bind. To me it seems obvious if you just pass the function this, then all will be right, but as it turns out, nothing works, and if you pass bind (this.function.bind(this, args)), it works.

Help to understand what was happening, please explain the following solution:

"use strict";

function ask(question, answer, ok, fail) {
 var result = prompt(question, ");
 if (result.toLowerCase() == answer.toLowerCase()) ok();
 else fail();
}

var user = {
 login: 'Vasily',
 password: '12345',

 // method to call from ask
 loginDone: function(result) {
 console.log( this.login + (result ? 'entered the site' : 'login failed') );
},

 checkPassword: function() {
 ask("Your password?" this.password
 this.loginDone.bind(this, true)
,
 this.loginDone.call(this, false)
);
}
};

var vasya = user;
user = null;
vasya.checkPassword();
July 9th 19 at 10:04
2 answers
July 9th 19 at 10:06
The bind method binds the context to a specific feature, and since you pass the function outside the object when you call this function if you do not bind the context, this will refer to the area where this function is called.
+ in the bind method you can just pass the arguments and the function will fail because bind returns a short.
If anything, I can help Skype: lithium100500
Then please explain what context will passed to the function loginDone, if not to bind the context, passing in just this.loginDode(true/false)?

And please explain why the won't work if you just explicitly specify the object, passing in like so: user.loginDone(true/false)? - Howell commented on July 9th 19 at 10:09
: The context is "undefined". And just pass this.loginDode(true/false) will not work, because you already called this function, as I said in the case of bind, you pass a closure and then call this function with the previously sent parameters. About the user.loginDone(true/false) is the same as this.loginDone(true/false) you already call the function. - gloria commented on July 9th 19 at 10:12
July 9th 19 at 10:08
Namely how exactly is the loss of context?


You can call a function in another context:

var foo = {
 bar: function () {
console.log(this);
}
};
var bar = { bar: foo.bar };
foo.bar(); // call the function in the context of foo.
bar.bar(); // call the function but in the context bar


In your case you need to explicitly pass a context to the nested anonymous function.

Find more questions by tags JavaScript