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.
This will create a string:
But
thisis 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 useconsole.dir(this).