2016-03-22 37 views
0
var workViewer = { 
    container: document.documentElement, 
    popup: document.querySelector('.avgrund-popup'), 
    cover: document.querySelector('.avgrund-cover'), 

    init: function() { 
     this.addClass(this.container, 'avgrund-ready'); 
     window.avgrund = { 
      activate: this.activate, 
      deactivate: this.deactivate, 
      disableBlur: this.disableBlur 
     }; 
    }, 
    activateModal: function (state) { 
     setTimeout(function() { 
      this.parent.removeClass(popup, 'no-transition'); //this line 
      this.parent.addClass(this.container, 'avgrund-active'); //this line 
     }, 0); 
    }, 


    removeClass: function (element, name) { 
     element.className = element.className.replace(name, ''); 
    } 
}; 


module.exports = workViewer; 

我想将这个转换成setTimeout函数,怎么办呢?如何将此传递给JavaScript中的SetTimeout()函数?

这是我的第一篇文章,请让我知道如果我能以任何方式

+0

'var that = this;函数(){that.parent ...' – user234461

+0

谢谢!这是我正在寻找的。 –

回答

3

有两种主要方式。首先是节约了参考this,并用它来代替:

var self = this; 
setTimeout(function() { 
    self.parent.removeClass(popup, 'no-transition'); 
    self.parent.addClass(self.container, 'avgrund-active'); 
}, 0); 

另一种是使用bind创建一个新的功能与this绑定到给定值。

setTimeout(function() { 
    this.parent.removeClass(popup, 'no-transition'); 
    this.parent.addClass(this.container, 'avgrund-active'); 
}.bind(this), 0); 

如果您在支持它们的环境中运行,还可以使用arrow function

setTimeout(() => { 
    this.parent.removeClass(popup, 'no-transition'); 
    this.parent.addClass(this.container, 'avgrund-active'); 
}, 0); 
+1

很好的回答!谢谢! –

2

您可以使用Function.prototype.bind()改善。它创建了与给定上下文有关的功能:

setTimeout(function() { 
    this.parent.removeClass(popup, 'no-transition'); //this line 
    this.parent.addClass(this.container, 'avgrund-active'); //this line 
}.bind(this), 0); 
+0

太好了,谢谢! –

相关问题