【问题标题】:Javascript - setting interval during object creation and referring to property using "this"Javascript - 在对象创建期间设置间隔并使用“this”引用属性
【发布时间】:2014-03-27 10:20:08
【问题描述】:

我有两个问题。

是否可以在此对象内部为对象方法创建间隔?

下面是更好地说明问题的代码:

var Counter_01 = {
    start_number: 0,
    countUp: function() {
        document.getElementById('display').innerHTML = this.start_number;
        this.start_number++;
    },
    // is it possible to create interval for countUp function here?
}

第二个问题是,是否可以在对象创建期间运行函数,使用对象内部的间隔?

代码:

function Counter() {
    this.start_number = 0;
    this.countUp = function() {
        document.getElementById('display').innerHTML = this.start_number; // code works when instead of "this.start_number" there is direct reference to the object name like "Counter_02.start_number"
        this.start_number++; // the same here
    }
    this.interval = setInterval(this.countUp, 1000);
}       
var Counter_02 = new Counter();

当此代码运行时,网络浏览器中只会显示“NaN”,而不是递增数字。

我试图使用参数传递对象名称,但它不起作用...

代码:

function Counter( name ) {
    this.start_number = 0;
    this.countUp = function() {
        document.getElementById('display').innerHTML = name.start_number;
        name.start_number++;
    }
    this.interval = setInterval(this.countUp, 1000);
}
var Counter_02 = new Counter( 'Counter_02' );

如何编写代码,允许在对象创建期间运行间隔,而不直接引用创建的对象名称?

我刚刚开始使用 javascript,我将不胜感激。

【问题讨论】:

  • setInterval 中尝试this.countUp.bind(this)

标签: javascript object this setinterval


【解决方案1】:

使用setTimeout函数:

function Counter_01 () {
    this.start_number = 0,
    this.countUp = function() {
        document.getElementById('display').innerHTML = this.start_number;
        this.start_number++;
        setTimeout(this.countUp, 2000);//two seconds waiting
    }
    this.countUp();
}

如果您需要为countUp 添加一些参数,请使用

setTimeout(function(){ this.countUp('argument') } , 2000);

【讨论】:

  • 当我将“this.countUp”更改为“this.countUp.bind(this)”并第一次使用“Counter_01.countUp();”手动运行函数时,它可以工作。我还有一个问题:是否可以在对象内部运行函数,而不是从外部手动运行?
  • 为什么不使用函数而不是对象?因此,您可以“自动”启动 countUp 功能。我编辑了我的帖子。
  • 我在此处附加的这个简单示例不是我要创建的主程序。这个计数器只是我想提出我的问题的一个例子。 :) 假设有一个对象,它有 10 个不同的功能。当使用“var object = {//some code};”创建对象时有没有办法让所有功能自动运行?还是有必要从外部手动启动它们?现在我认为实现我想要的最好方法是使用创建对象的函数,就像我的第二个示例代码一样,并在那里使用“this.countUp.bind(this)”。
猜你喜欢
  • 2019-06-18
  • 1970-01-01
  • 2012-03-13
  • 1970-01-01
  • 2018-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多