Javascript: 'this' changes when assigning a property?

Posted by Pickels on Stack Overflow See other posts from Stack Overflow or by Pickels
Published on 2010-05-23T23:49:55Z Indexed on 2010/05/24 0:00 UTC
Read the original article Hit count: 195

Filed under:

I know 'this' can be a problem when you don't understand Javascript well but this one got me a little puzzled.

var ControlTypes = {
    TextBox: function () {
        console.log(this);
        this.Name = "TextBox";
        console.log(this);
    }
}

ControlTypes.TextBox();

Firebug gives the following result:

Object {}
Object { Name="TextBox"}

The first object is ControlTypes and the second one is Textbox. Could anybody explain the behavior behind this?

© Stack Overflow or respective owner

Related posts about JavaScript