JavaScript:对象的问题

时间:2011-07-31 16:05:58

标签: javascript jquery

我正在编程一个小计时器。代码如下:

var counter = {
    seconds: 100,
    clock: function () {
        $('input').val(this.seconds);
        this.seconds -= 1;
        setTimeout(this.clock(), 1000);
    }
};

counter.clock();

http://jsfiddle.net/4ktEG/

上有一个工作示例

不知何故,每次运行代码时,我都会得到不同的答案。有什么问题?

6 个答案:

答案 0 :(得分:7)

这是您正在寻找的倒计时。

var counter = {
    seconds: 100,
    clock: function () {
        $('input').val(this.seconds);
        this.seconds -= 1;
        setTimeout(function(){counter.clock()}, 1000);
    }
};

counter.clock();

http://jsfiddle.net/4ktEG/13/

答案 1 :(得分:1)

jQuery使用jQuery.proxy()[docs]方法绑定this值。

setTimeout($.proxy(counter,'clock'), 1000);

$.proxy将返回一个调用counter.clockcounter绑定为this值的函数。


或者您可以像这样使用它将counter永久绑定到counter.clock

var counter = {
    seconds: 100
};

counter.clock = $.proxy( function () {
    $('input').val(this.seconds);
    this.seconds -= 1;
    setTimeout(this.clock, 1000);
}, counter);

counter.clock();

示例: http://jsfiddle.net/bmYAN/

答案 2 :(得分:0)

使用:

var counter = {
    seconds: 100,
    clock: function () {
        $('input').val(counter.seconds);
        counter.seconds -= 1;
        setTimeout(counter.clock, 1000);
    }
};

counter.clock();

你在函数中使用了“this”,你想要的是引用“counter”对象。

答案 3 :(得分:0)

如果您希望输入显示“100”,则在调用setTimeout时消失,那么您必须取出“this.clock()”上的括号

为此:

var counter = {
seconds: 100,
clock: function () {
    $('input').val(this.seconds);
    this.seconds -= 1;
    setTimeout(this.clock, 1000);
}
};

counter.clock();

答案 4 :(得分:0)

当你说

setTimeout(this.clock(), 1000); //the clock method will be called right away.

改为使用

setTimeout(this.clock, 1000); 

答案 5 :(得分:0)

超时将在全局上下文中执行。因此,处理程序中的'this'将引用全局上下文。您必须将函数绑定到所需的上下文以获得所需的结果。查看带有上下文参数的function.callfunction.apply

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();