This commit is contained in:
Ilya Kantor 2017-03-27 01:24:15 +03:00
parent c8b560d1f4
commit 5f340d0545
7 changed files with 312 additions and 306 deletions

View file

@ -0,0 +1,16 @@
1. Either use a wrapper function, an arrow to be concise:
```js
askPassword(() => user.login(true), () => user.login(false));
```
Now it gets `user` from outer variables and runs it the normal way.
2. Or create a partial function from `user.login` that uses `user` as the context and has the correct first argument:
```js
askPassword(user.login.bind(user, true), user.login.bind(user, false));
```

View file

@ -0,0 +1,34 @@
importance: 5
---
# Partial application for login
The task is a little more complex variant of <info:task/question-use-bind>.
The `user` object was modified. Now instead of two functions `loginOk/loginFail`, it has a single function `user.login(true/false)`.
What to pass `askPassword` in the code below, so that it calls `user.login(true)` as `ok` and `user.login(fail)` as `fail`?
```js
function askPassword(ok, fail) {
let password = prompt("Password?", '');
if (password == "rockstar") ok();
else fail();
}
let user = {
name: 'John',
login(result) {
alert( this.name + (result ? ' logged in' : ' failed to log in') );
}
};
*!*
askPassword(?, ?); // ?
*/!*
```
Your changes should only modify the highlighted fragment.