2017-10-25 12 views
0

OO Javascriptでタイプライターエフェクトを作成しています。私はProceduralで同じコードを試してみました。しかし何らかの理由で、OOではうまくいきませんでした。私を助けてください。手続きprototype関数をjavascriptで2回以上実行できないのはなぜですか?

var string = 'Hello World! Do you like this effect?'; 
 
var animField = document.getElementById('demo'); 
 
var counter = 1; 
 
var speed = 75; 
 

 
function typeWriter(){ 
 
\t if(counter <= string.length){ 
 
\t \t animField.innerHTML = string.substr(0, counter); 
 
\t \t counter++; 
 
\t \t setTimeout(typeWriter, speed); 
 
\t } 
 
} 
 

 
typeWriter();
\t <p id = "demo"></p>

オブジェクト指向Javascriptのコード:

var Typewriters = function(string, speed, printEffect){ 
 
\t this.string = string; 
 
\t this.counter = 1; 
 
\t this.speed = speed; 
 
\t this.printEffect = printEffect; 
 
}; 
 

 
Typewriters.prototype.typeWriter = function() { 
 
\t if(this.counter <= this.string.length){ 
 
\t \t this.printEffect.innerHTML = this.string.substr(0, this.counter); 
 
\t \t this.counter++; 
 
\t \t setTimeout(this.typeWriter, this.speed); // Problem is here 
 
\t } 
 
}; 
 

 
var settings = new Typewriters('Hello World! Do you like this effect?', 75, document.getElementById('demo')); 
 
settings.typeWriter();
<p id = "demo"></p>

私を助けてください。あなたがそれを説明するなら、それはすばらしいでしょう。

答えて

1

this変数のコンテキストが失われました。 .bind()を使用してください。

var Typewriters = function(string, speed, printEffect){ 
 
\t this.string = string; 
 
\t this.counter = 1; 
 
\t this.speed = speed; 
 
\t this.printEffect = printEffect; 
 
}; 
 

 
Typewriters.prototype.typeWriter = function() { 
 
\t if(this.counter <= this.string.length){ 
 
\t \t this.printEffect.innerHTML = this.string.substr(0, this.counter); 
 
\t \t this.counter++; 
 
\t \t setTimeout(this.typeWriter.bind(this), this.speed); // Problem is here 
 
\t } 
 
}; 
 

 
var settings = new Typewriters('Hello World! Do you like this effect?', 75, document.getElementById('demo')); 
 
settings.typeWriter();
<p id = "demo"></p>

+0

HAHAH!ダブありがとう。 – Sanjay

関連する問題