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>
<ul> <li>http://coursesweb.net/html/</li> <li>http://coursesweb.net/css/</li> </ul>
.some_class { display: list-item; }
var obj = { "courses": ["php", "javascript", "ajax"] }; var jsonstr = JSON.stringify(obj); alert(jsonstr); // {"courses":["php","javascript","ajax"]}
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>'; $dochtml = new DOMDocument(); $dochtml->loadHTML($strhtml); $elm = $dochtml->getElementById("dv1"); echo $elm->nodeValue; // CoursesWeb.net