"this" in JavaScript

Posted by cf_PhillipSenn on Stack Overflow See other posts from Stack Overflow or by cf_PhillipSenn
Published on 2010-12-27T18:42:44Z Indexed on 2010/12/27 18:53 UTC
Read the original article Hit count: 121

Filed under:

I'm trying to understand the syntax of how to put together a JavaScript function as an object.

Q: Is this the right way to do it?

The reason why I ask is because I'm looking at it in Firebug and I was hoping to be able to drill down and see the value of myVar and myVariable, but instead Firebug only says that "this" is an object Object.

var myObject = {
    init: function() {
        var myVar = 1;
        myObject.myVariable = 2;
        console.log('"this" when called as an object: ' + this);
    }
}
myObject.init();

Also, what's the funny little syntax to call it directly upon declaration? Something about (), but when I remove the last line and put () at the end of the declaration, I get a syntax error.

© Stack Overflow or respective owner

Related posts about JavaScript