Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Повторение метода экземпляра класса (https://javascript.ru/forum/misc/66527-povtorenie-metoda-ehkzemplyara-klassa.html)

polin11 21.12.2016 01:26

Повторение метода экземпляра класса
 
Есть класс, нужно чтобы имя экземпляра выводилось в DOM с промежутком 1 сек. Есть прекрасные функции setInterval, setTimeout.
Пробовал так
<html>
<head>
<script type="text/javascript">
function animal()
{
    this.name="WOLF";
}
animal.prototype.repeat=function(){
	console.log(this);
	document.getElementById('target').innerHTML+=this.name+'<br/>';
}
document.addEventListener('DOMContentLoaded', function () {
var ex=new animal();

setInterval(ex.repeat(), 1000); //отображается 1 раз имя на странице и в консоль 

});
</script>
</head>
<body>
<div id="target"></div>
</body>
</html>

Еще так
<html>
<head>
<script type="text/javascript">
function animal()
{
    this.name="WOLF";
}
animal.prototype.repeat=function(){
	console.log(this);
	document.getElementById('target').innerHTML+=this.name+'<br/>';
	setInterval(this.repeat(), 1000); //На страницу и в консоль не выводит, браузер зависает
}
document.addEventListener('DOMContentLoaded', function () {
var ex=new animal();
ex.repeat();
});
</script>
</head>
<body>
<div id="target"></div>
</body>
</html>

И так:

<html>
<head>
<script type="text/javascript">
function animal()
{
    this.name="WOLF";
}
animal.prototype.repeat=function(){
	console.log(this);
	document.getElementById('target').innerHTML+=this.name+'<br/>';
	setTimeout(this.repeat(), 1000); //В консоль выводит, но на страницу нет, браузер зависает
}
document.addEventListener('DOMContentLoaded', function () {
var ex=new animal();
ex.repeat();
});
</script>
</head>
<body>
<div id="target"></div>
</body>
</html>

Помогите как сделать

рони 21.12.2016 02:19

polin11,
<html>
<head>
<script type="text/javascript">
function animal()
{
    this.name="WOLF";
}
animal.prototype.repeat=function(){
  var self = this;
  document.getElementById('target').innerHTML+=this.name+'<br/>';
  setTimeout(self.repeat.bind(self), 1000);
}
document.addEventListener('DOMContentLoaded', function () {
var ex=new animal();
ex.repeat();
});
</script>
</head>
<body>
<div id="target"></div>
</body>
</html>


Часовой пояс GMT +3, время: 13:42.