views:

74

answers:

1

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:

  1. Does 'this' keyword refers always to the outer scope's housing even inside the inner functions?

  2. 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

+2  A: 

this is determined by the invocation pattern, that is, how a function object is being called.

There are 4 different kinds of invocation patterns:

  1. method invocation: function are defined as a property of some object, and is called via the object using refinement, that is, ..

    a.func(); // this refers to the object, i.e., a.

  2. function invocation: plain function call.

    func(); // this is bond to the global object.

  3. constuctor invocation: well, it is a little complicated. Since constructors are used as, well, the consturctor method for the new function objects being new, this refers to the new function object being created.

    var func = new Func(); // this refers to func while in Func constructor)

  4. apply invocation:

    func.apply(thisArg, argArray); // this is 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.

bryantsai
Thanks, it is really useful information.you can finds some more about invocation patterns in this article:http://mcarthurgfx.com/blog/article/4-ways-functions-mess-with-this
burak ozdogan
And this one is also quite explanatory: Function invocation in JavaScript - contexts revisited - http://msmvps.com/blogs/luisabreu/archive/2009/08/24/function-invocation-in-javascript-contexts-revisited.aspx
burak ozdogan