Perché non posso utilizzare setTimeout
in un oggetto javascript?Come utilizzare "setTimeout" per richiamare l'oggetto stesso
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 ??????
};
}
Grazie per Steve`s Solution, ora funzionerà se il codice è la seguente ... perché il 'questo' prima era in realtà che punta alla funzione all'interno setTimeOut, non può Messaggio 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);
};
}
Ma perché doesn`t funziona se facciamo questo:
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);
}
}
possibile duplicato di [Come accedere al corretto 'this'/contesto all'interno di un callback?] (Http://stackoverflow.com/q/20279484/1048572) – Bergi
Duplicati: [setTimeout() all'interno della classe JavaScript che utilizza" questo "] (Http://stackoverflow.com/questions/5911211/settimeout-inside-javascript-class-using-this) e [Utilizzo di setTimeout() all'interno di una funzione di classe JavaScript] (http://stackoverflow.com/questions/ 6997921/using-settimeout-in-a-javascript-class-function) – handle