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;
Run Code Online (Sandbox Code Playgroud)
我想通过这个进setTimeout函数,什么做的正确方法?
这是我的第一篇文章,请让我知道我是否可以以任何方式进行改进
有两种主要方法。首先是保存对引用this并改为使用它:
var self = this;
setTimeout(function() {
self.parent.removeClass(popup, 'no-transition');
self.parent.addClass(self.container, 'avgrund-active');
}, 0);
Run Code Online (Sandbox Code Playgroud)
另一种是用于bind创建this绑定到给定值的新函数。
setTimeout(function() {
this.parent.removeClass(popup, 'no-transition');
this.parent.addClass(this.container, 'avgrund-active');
}.bind(this), 0);
Run Code Online (Sandbox Code Playgroud)
如果您在支持它们的环境中运行,也可以使用箭头功能。
setTimeout(() => {
this.parent.removeClass(popup, 'no-transition');
this.parent.addClass(this.container, 'avgrund-active');
}, 0);
Run Code Online (Sandbox Code Playgroud)