Это просто хороший домашнее задание, я сделаю это для вас;) Пожалуйста, посмотрите на мое решение:
function Counter() {
this.currentCount = 0;
this.conditions = [];
this.interval = undefined;
}
Counter.prototype.start = function() {
if (!this.interval) {
var that = this;
this.interval = setInterval(function() {
that.update();
}, 1000);
}
};
Counter.prototype.stop = function() {
if (this.interval) {
clearInterval(this.interval);
this.interval = undefined;
}
this.currentCount = 0;
};
Counter.prototype.when = function(value, callback) {
var that = this;
this.conditions.push(function() {
if (that.currentCount === value) {
callback.call(that, value);
}
});
};
Counter.prototype.update = function() {
this.currentCount++;
for (var i = 0, l = this.conditions.length; i < l; i++) {
var condition = this.conditions[i];
condition();
}
};
var counter = new Counter();
counter.when(50, function(value) {
console.log('We arrived at ' + value + ', the requested value.');
});
counter.when(60, function (value) {
console.log('Stop at ' + value + '!');
this.stop();
});
counter.start();
и это fiddled!
Другой ответ здесь дал хороший аргумент в сокрытии частных переменных, но реализовал его немного смущенно, так что это еще один способ сделать его похожим. Вместо общих функций прототипа это использует функции экземпляра. Некоторые могут сказать, что это требует большего объема памяти, но я не считаю, что это важно, и позволяет легко иметь рядовых в реальной функции конструктора.
var Counter = function() {
var that = this, currentCount = 0,
conditions = [], interval;
var update = function() {
currentCount++;
for (var i = 0, l = conditions.length; i < l; i++) {
var condition = conditions[i];
condition();
}
};
this.start = function() {
if (!interval) {
interval = setInterval(function() {
update.call(that);
}, 1000);
}
};
this.when = function (value, callback) {
conditions.push(function() {
if (currentCount === value) {
callback.call(that, value);
}
});
};
this.stop = function() {
if (interval) {
clearInterval(interval);
interval = undefined;
}
currentCount = 0;
};
};
var counter = new Counter();
counter.when(50, function(value) {
console.log('We arrived at ' + value + ', the requested value.');
});
counter.when(60, function (value) {
console.log('Stop at ' + value + '!');
this.stop();
});
counter.start();
посмотреть его fiddled!
Обратите также внимание, что в обоих примерах counter
является instanceof Counter
и Object
,
тогда Counter
является instanceof Function
и Object
(почему мне нравится писать так много кода;))
Что вы цените? пройденное время ? html input? ... –
ну в этом примере он просто вернет значение, первоначально заданное для – Josh