Показать сообщение отдельно
  #1 (permalink)  
Старый 28.01.2016, 13:54
Интересующийся
Отправить личное сообщение для uanr81 Посмотреть профиль Найти все сообщения от uanr81
 
Регистрация: 14.12.2015
Сообщений: 18

Из книги Фленаган
Здравствуйте. В книге Фленагана есть листинг
function Range(from, to) {
    this.from = from;
    this.to = to;
}
Range.prototype = {
    includes: function(x) { return this.from <= x && x <= this.to; },
    foreach: function(f) {//(**)
        for(var x = Math.ceil(this.from); x <= this.to; x++) f(x);//(***)
    },
    toString: function() { return "(" + this.from + "..." + this.to + ")"; }
};
var r = new Range(1,3);   
r.includes(2);            
r.foreach(console.log); //(**)  
console.log(r);
В строке (***) при запуске в Chrome ошибка. Проясните почему? Если изменить немного код определения функции в строке (**) то сработает
function consoleLog(){// обвертываем console.log
	return function(x){
		console.log(x);
	}
}
function Range(from, to) {
    this.from = from;
    this.to = to;
}
Range.prototype = {
    includes: function(x) { return this.from <= x && x <= this.to; },
    foreach: function(func) {
        var ff = func();//разворачиваем обвёртку 
		for(var x = Math.ceil(this.from); x <= this.to; x++) ff(x);
    },
    toString: function() { return "(" + this.from + "..." + this.to + ")"; }
};
var r = new Range(1,3);   
r.includes(2);            
r.foreach(consoleLog); //передаём в аргумент обвертку  
console.log(r);
Ответить с цитированием