setTimeout()
can be used to call a function after a specified time, and to auto-call a function multiple times, if it is added inside it. But, setTimeout()
causes javascript to use the global scope, and this can be a problem when it is used inside a class, because it cannot be used with the special word this
.
setTimeout()
not works as we expect.
<h4>Example this in setTimeout()</h4> <div id="swprop"></div> <script> // defines a class function class className { constructor(){ this.prop = 0; } // method metName() { document.getElementById('swprop').innerHTML = this.prop; // shows prop value in #swprop // adds one unit to prop to each call, and auto-calls this function every 0.5 sec., till prop reaches 10 this.prop++; if(this.prop < 10) setTimeout('this.metName()', 500); } } // creates an object of className, and accesses metName() var objTest = new className(); objTest.metName(); </script>
setTimeout()
is scoping via itself.The solution is to apply the bind(val)
method, which has its this
keyword set to the provided value (val).
- So, in setTimeout()
use this syntax:
<h4>Example bind() method in setTimeout()</h4> <div id="swprop"></div> <script> // defines a class function class className { constructor(){ this.prop = 0; } // method metName() { document.getElementById('swprop').innerHTML = this.prop; // shows prop value in #swprop // adds one unit to prop to each call, and auto-calls this function every 0.5 sec., till prop reaches 10 this.prop++; if(this.prop < 10) setTimeout(this.metName.bind(this), 500); } } // creates an object of className, and accesses metName() var objTest = new className(); objTest.metName(); </script>
<embed src="flash_game.swf" width="450" height="350" />
#id:first-line { font-weight: bold; color: blue; }
var url = window.location; alert(url);
$homepage = file_get_contents("http://coursesweb.net/"); echo $homepage;