2

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.

Phillip Senn
  • 46,771
  • 90
  • 257
  • 373

3 Answers3

3

This will create a string:

'"this" when called as an object: ' + this 

But this is not a string, so its toString() prototype gets called. That's why you only see [object Object].

If you want to have Firebug display the actual object, do a simple console.log(this) or to see the contents directly use console.dir(this).

Ivo Wetzel
  • 46,459
  • 16
  • 98
  • 112
2

The "funny little syntax" doesn't really apply here, because you're not really creating a "function object" — that's just an object with a property whose value is a reference to a function object.

However, though it's been done to death on Stackoverflow, you're probably talking about something like this:

var myobject = (function() {
  var something = { whatever: "for example" };
  return {
    init: function() {
      this.foo = "hello";
      // initialize
    },
    getSomething: function() { return something.whatever; }
  };
})();

Now "myobject" is initialized by a call to an anonymous function, which will be thrown away right after that statement. The closure formed by the function invocation, however, remains alive.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • "though it's been done to death on Stackoverflow".

    I'm not sure I even know how to frame the question so that I can see similar questions.

    – Phillip Senn Dec 27 '10 at 18:58
  • Well I tried a question about "this" and the SO search thing found [this old question about immediately-invoked anonymous functions](http://stackoverflow.com/questions/1634268/explain-javascripts-encapsulated-anonymous-function-syntax) – Pointy Dec 27 '10 at 19:06
1

Here is a nice reference for JavaScript object creation

brildum
  • 1,759
  • 2
  • 15
  • 22