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>
<table><tr> <th>Title 1</th> <th>Title 2</th> </tr></table>
.some_class { line-height: 150%; }
document.getElementById("id_button").onclick = function(){ window.open("http://coursesweb.net/"); }
$ar_dir = scandir("dir_name"); var_export($ar_dir);