【问题标题】:set Interval function not working as method [duplicate]设置间隔函数不作为方法工作[重复]
【发布时间】:2018-10-23 04:01:27
【问题描述】:

谁能告诉我为什么setInterval 在这段代码中不起作用。我可能遗漏了一些东西,我不确定它是什么。我正在尝试运行方法args.counts();

错误是:

未捕获的类型错误:this.cast 不是 Caste.log 中的函数 (prototype.js:17)

    function Caste(){
    this.name = 'James';
    this.surname = 'Penn';
    this.age = 38;

    this.one = document.getElementById('one');
    this.two = document.getElementById('two');

    this.cast = function(){
         return  this.age;
    }
    // ------------------------

    this.log = function(){
        console.log(this.cast());
    }
    // ------------------------
    this.display = function(){
        this.one.innerHTML = this.age;
    }

    this.counts = function(){
     (setInterval(this.log, 2000));
    }
}

// ----------------------

let args = new Caste();
args.counts();

【问题讨论】:

  • 昆汀,你能给我看看副本吗
  • Kingsley Ajebon 他刚刚做了......使用欺骗链接(顺便说一句,即使问题不一样,它也可以关闭,但答案解决了两者)
  • 好的。见过。在我回复之前,页面没有完全加载。谢谢。

标签: javascript oop object methods constructor


【解决方案1】:

setIntervalwindow.setInterval的简写,表示调用上下文是window,而不是实例化的对象。将函数绑定到实例化对象:

(setInterval(this.log.bind(this), 2000));

或者使用箭头函数:

(setInterval(() => this.log(), 2000));

【讨论】:

  • 优秀。希望版主离开这个帖子。从新手的角度来看,这似乎是一种不同的答案。
猜你喜欢
  • 1970-01-01
  • 2016-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-21
  • 1970-01-01
  • 2021-11-22
相关资源
最近更新 更多