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() d开发者_JAVA技巧oes 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
this is determined by the invocation pattern, that is, how a function object is being called.
There are 4 different kinds of invocation patterns:
method invocation: function are defined as a property of some object, and is called via the object using refinement, that is,
..a.func(); //
thisrefers to the object, i.e.,a.function invocation: plain function call.
func(); //
thisis bond to the global object.constuctor invocation: well, it is a little complicated. Since constructors are used as, well, the consturctor method for the new function objects being
new,thisrefers to the new function object being created.var func = new Func(); //
thisrefers tofuncwhile inFuncconstructor)apply invocation:
func.apply(thisArg, argArray); //
thisis bond to the first argument
In another words, the this in your example all refers to the global object (your onClick call Other()). You should try using new Other() instead.
加载中,请稍侯......
精彩评论