如何将上下文传递给setTimeout?我想打电话this.tip.destroy(),如果this.options.destroyOnHide在1000毫秒.我怎样才能做到这一点?
if (this.options.destroyOnHide) {
setTimeout(function() { this.tip.destroy() }, 1000);
}
Run Code Online (Sandbox Code Playgroud)
当我尝试以上时,this指的是窗口.
为什么我不能setTimeout在javascript对象中使用?
Message = function () {
...
...
this.messageFactory = ...
this.feedbackTag = document.getElementById('feedbackMessages');
this.addInfo = function (message) {
var info = this.messageFactory.createInfo(message); // create a div
this.feedbackTag.appendChild(info);
setTimeout('this.feedbackTag.removeChild(info)', 5000);
// why in here, it complain this.feedbacktag is undefined ??????
};
}
Run Code Online (Sandbox Code Playgroud)
感谢Steve的解决方案,现在如果代码如下所示它将起作用...因为之前'this'实际指向setTimeOut中的函数,它不能重新发送消息.
Message = function () {
...
...
this.messageFactory = ...
this.feedbackTag = document.getElementById('feedbackMessages');
this.addInfo = function (message) {
var info = this.messageFactory.createInfo(message); // create a div
this.feedbackTag.appendChild(info);
var _this = this;
setTimeout(function() { _this.feedbackTag.removeChild(info); }, …Run Code Online (Sandbox Code Playgroud)