Tại sao tôi không thể sử dụng setTimeout
trong đối tượng javascript?Cách sử dụng "setTimeout" để gọi chính đối tượng
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 ??????
};
}
Cám ơn Steve`s Solution, bây giờ nó sẽ làm việc nếu mã là như sau ... vì 'này' trước đã thực sự trỏ đến các chức năng trong setTimeout, nó có thể không nhắn rearch.
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); }, 5000);
};
}
Nhưng tại sao doesn `t cho nó hoạt động nếu chúng ta làm điều này:
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);
}
}
có thể trùng lặp của [Cách truy cập đúng 'this'/context bên trong một cuộc gọi lại?] (Http://stackoverflow.com/q/20279484/1048572) – Bergi
Trùng lặp: [setTimeout() bên trong JavaScript Lớp bằng cách sử dụng" this ”] (Http://stackoverflow.com/questions/5911211/settimeout-inside-javascript-class-using-this) và [Sử dụng setTimeout() trong một hàm lớp JavaScript] (http://stackoverflow.com/questions/ 6997921/sử dụng-settimeout-trong-a-javascript-class-chức năng) – handle