How to use “setTimeout” to invoke object itself

前端 未结 3 843
心在旅途
心在旅途 2020-12-01 04:37

Why can\'t I use setTimeout in a javascript object?

Message = function () {

    ...
    ...        

    this.messageFactory = ...
    this.fee         


        
3条回答
  •  鱼传尺愫
    2020-12-01 05:26

    To answer your last question: "Why doesn`t it work if we do this":

    Message = function () {
    
    ...
    ...        
    
    this.messageFactory = ...
    this.feedbackTag = document.getElementById('feedbackMessages');
    // public function
    this.addInfo = function (message) {
        var info = this.messageFactory.createInfo(message); // create a div
        this.feedbackTag.appendChild(info);
    
        delayRemove(info);
    
    };
    // private function
    function delayRemove(obj) {
        var _this = this;
        setTimeout(function() { _this.feedbackTag.removeChild(info); }, 5000);
    }}
    

    It's not working because you are passing an undefined variable (info) instead of a defined variable (obj). Here is the corrected function:

    function delayRemove(obj) {
    var _this = this;
    setTimeout(function() { _this.feedbackTag.removeChild(obj); }, 5000);}
    

提交回复
热议问题