13
Situation
I was riding a widget when I started to analyze a possible error, because by the tests actually occurred :
Testing
document.getElementById('teste').addEventListener('click', function(){
n.p.call(this);
setTimeout(function(){
document.getElementById('result').innerHTML = 'FAIL';
n.q.call(this);
},2000);
});
var n = {
options : {
move : true,
},
p : function(){
console.log(this);
document.getElementById('result').innerHTML = this;
},
q : function(){
if(this.options.move === true){
console.log()
document.getElementById('result').innerHTML = 'OK';
}
}
}
n.p();
setTimeout(function(){
n.q();
},2000);
<p id="teste">
teste
</p>
<div id="result">
</div>
Description
The methods of n at first should be called via n. p. (), that is function, however I remembered the method call and apply, that alter the this, to the calling object.
Doubt
- How to reference this, whereas this is not what I expected?
- I must always do object.var instead of this var.?
+1, very good implementation, with this confirms me that I must be careful with the this.
– Guilherme Lautert