<script> funzione=function(){ setInterval(function(){document.body.innerHTML+=this},4000); } funzione(); </script> <body></body>Output:
[object Window][object Window][object Window][object Window]Per setInterval this corrisponde all'oggetto window.
Ora creo un oggetto questo istanziando un costruttore oggetto.
Nel contesto del costruttore, la funzione funzione evoca setInterval.
<script> var oggetto=function(){ this.funzione=function(){ setInterval(function(){document.body.innerHTML+=this},4000); } } questo=new oggetto(); questo.funzione(); </script> <body></body>Nonostante la funzione setInterval sia evocata da un metodo interno all'oggetto, per lei this si riferisce sempre all'oggetto window.
Piccola variante:
<script> var oggetto=function(){ this.funzione=function(){ alert(this); setInterval(function(){document.body.innerHTML+=this},4000); } } questo=new oggetto(); questo.funzione(); </script> <body></body>Ecco: una volta evocata la funzione funzione; metodo dell'oggetto, io le chiedo di dirmi cosa è per lei this, e mi risponde che per lei this è [object Object], quindi la funzione evoca setInterval che dice che per lei invece this è [object Window].
Nessun commento:
Posta un commento