en.javascript.info/1-js/6-objects-more/7-bind/6-ask-currying/solution.md
2015-01-14 10:23:45 +03:00

69 lines
No EOL
1.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Решение с bind
Первое решение -- передать в `ask` функции с привязанным контекстом и аргументами.
```js
//+ run
"use strict";
function ask(question, answer, ok, fail) {
var result = prompt(question, '');
if (result.toLowerCase() == answer.toLowerCase()) ok();
else fail();
}
var user = {
login: 'Василий',
password: '12345',
loginDone: function(result) {
alert(this.login + (result ? ' вошёл в сайт' : ' ошибка входа'));
},
checkPassword: function() {
*!*
ask("Ваш пароль?", this.password, this.loginDone.bind(this, true), this.loginDone.bind(this, false));
*/!*
}
};
user.checkPassword();
```
# Решение с локальной переменной
Второе решение -- это скопировать `this` в локальную переменную (чтобы внешняя перезапись не повлияла):
```js
//+ run
"use strict";
function ask(question, answer, ok, fail) {
var result = prompt(question, '');
if (result.toLowerCase() == answer.toLowerCase()) ok();
else fail();
}
var user = {
login: 'Василий',
password: '12345',
loginDone: function(result) {
alert(this.login + (result ? ' вошёл в сайт' : ' ошибка входа'));
},
checkPassword: function() {
var self = this;
*!*
ask("Ваш пароль?", this.password,
function() { self.loginDone(true); },
function() { self.loginDone(false); }
);
*/!*
}
};
user.checkPassword();
```
Оба решения хороши, вариант с `bind` короче.