I have the structure below that I dont understand the output very well.
var asker = {
answer: "Its raining...",
askQuestion: function(answered){
console.log("Opps..." + this.answer);
answered();
}
}
//function literal
var debunker = function(){
answer = "Its cloudy...";
debunk = function(){
console.log(this);
console.log("No way! The real answer is:" + this.answer);
};
return {
debunk: debunk
};
}();
asker.askQuestion(debunker.debunk);
It gives me these outputs
Opps...Its raining...
DOMWindow
No way! The real answer is:Its cloudy...
The debunker.debunk gets the answer that is 'Its cloudy'. However this in the debunk function refers the DOMWindow so how this.answer can get the Its cloudy while it refers the window object ?
Read the introduction into the
thiskeyword. You execute the functionanswered()in global context. Asanswer(in your debunker constructor) is not a private variable, it will be a property of the globalwindowobject.