Hi,
Basically I am trying to understand and learn the 'this' keyword's working principle in JavaScript.
As far as I understand 'this' refers to the object (function) that it is inside at that moment.
So, by believing this, I wanted to test the output of the simple code below:
<body>
<input type="button" value="Add Age" onclick="Outer()" />
<script type="text/javascript">
function Outer(){
if(typeof this.Father == 'undefined')
{
this.Father = 0;
}
this.Father+=2;
alert(this.Father);
inner();
function inner(){
if(typeof this.Son== 'undefined')
{
this.Son = 0;
};
this.Son++;
alert(this.Son);
alert(this.Father);
};
};
</script>
</body>
And its output confuses me. Because in the inner() function, this.Son outputs the incremented integer value of the Son. But I expect this.Father to fail because inner() does not have a .Father attribute. But instead of throwing an exception it alerts the value of this.Father -Which seems
- a line above 'this' refers inner()
- and following line 'this' refers Outer()
At this point i have 2 questions in my mind actualy:
Does 'this' keyword refers always to the outer scope's housing even inside the inner functions?
And without having any instances declared 'this' keyword references what in the method? ( I mean without having something lik
var myFamily = new Outer()
)
Thanks,
burak ozdogan