JavaScript:对象的问题
我正在编程一个小定时器。代码如下:JavaScript:对象的问题,javascript,jquery,Javascript,Jquery,我正在编程一个小定时器。代码如下: var counter = { seconds: 100, clock: function () { $('input').val(this.seconds); this.seconds -= 1; setTimeout(this.clock(), 1000); } }; counter.clock(); 以一个关于 不知何故,每次我运行代码时,我都会得到不同的答案。有什么问题吗?使用
var counter = {
seconds: 100,
clock: function () {
$('input').val(this.seconds);
this.seconds -= 1;
setTimeout(this.clock(), 1000);
}
};
counter.clock();
以一个关于
不知何故,每次我运行代码时,我都会得到不同的答案。有什么问题吗?使用:
var counter = {
seconds: 100,
clock: function () {
$('input').val(counter.seconds);
counter.seconds -= 1;
setTimeout(counter.clock, 1000);
}
};
counter.clock();
您在函数中使用了“this”,您需要的是引用“counter”对象。这将执行您要查找的倒计时
var counter = {
seconds: 100,
clock: function () {
$('input').val(this.seconds);
this.seconds -= 1;
setTimeout(function(){counter.clock()}, 1000);
}
};
counter.clock();
如果您希望输入显示“100”,然后在调用setTimeout时消失,那么您必须取出“this.clock()”上的括号 因此:
var counter = {
seconds: 100,
clock: function () {
$('input').val(this.seconds);
this.seconds -= 1;
setTimeout(this.clock, 1000);
}
};
counter.clock();
当你说
setTimeout(this.clock(), 1000); //the clock method will be called right away.
用这个代替
setTimeout(this.clock, 1000);
超时将在全局上下文中执行。因此,处理程序中的“this”将引用全局上下文。您必须将函数绑定到所需的上下文才能获得所需的结果。查看
函数。调用或函数。应用带有上下文参数的
var counter = {
seconds: 100,
clock: function () {
$('input').val(this.seconds);
this.seconds -= 1;
var closure = function() {
counter.clock.call(counter);
};
setTimeout(closure, 1000);
}
};
counter.clock();
jQuery具有绑定这个值的方法
setTimeout($.proxy(counter,'clock'), 1000);
$.proxy
将返回一个调用计数器.clock
的函数,其中计数器
绑定为此
值
setTimeout($.proxy(counter,'clock'), 1000);
或者您可以这样使用它将计数器
永久绑定到计数器。时钟
:
var counter = {
seconds: 100
};
counter.clock = $.proxy( function () {
$('input').val(this.seconds);
this.seconds -= 1;
setTimeout(this.clock, 1000);
}, counter);
counter.clock();
示例:这可能会给你更多你想要的东西:我仍然没有做我想要的。它显示100,然后什么都没有。它有什么不同?请解释!那不是我想要的。我想要一个100、99、98等的计数器。没问题。一开始我以为发生了什么事,我把它作为评论而不是答案发布了出来。