Still confused about JavaScript's 'this'.

Posted by Nick Lowman on Stack Overflow See other posts from Stack Overflow or by Nick Lowman
Published on 2010-04-28T11:09:01Z Indexed on 2010/04/28 11:13 UTC
Read the original article Hit count: 610

Filed under:

I've been reading through quite a few articles on the 'this' keyword when using JavaScript objects and I'm still somewhat confused. I'm quite happy writing object orientated Javascript and I get around the 'this' issue by referring the full object path but I don't like the fact I still find 'this' confusing.

I found a good answer here which helped me but I'm still not 100% sure. So, onto the example. The following script is linked from test.html with <script src="js/test.js"></script>

if (!nick) {
    var nick = {};
}

nick.lowman = function(){
    var helloA = 'Hello A';
    console.log('1.',this, this.helloA);

    var init = function(){
        var helloB = 'Hello B';
        console.log('2.',this, this.helloB);
    }

    return {
        init: init
    }
}();

nick.lowman.init();

What kind of expected to see was

1. Object {} nick.lowman, 'Hello A'
2. Object {} init, 'Hello B'

But what I get is this?

1. Window test.html, undefined
2. Object {} init, undefined

I think I understand some of what's happening there but I would mind if someone out there explains it to me.

Also, I'm not entirely sure why the first 'console.log' is being called at all? If I remove the call to the init function //nick.lowman.init() firebug still outputs 1. Window test.html, undefined. Why is that? Why does nick.lowman() get called by the window object when the html page loads?

Many thanks

© Stack Overflow or respective owner

Related posts about JavaScript