How immediate object initialization works in JavaScript
Hey all, there's this line:
Code:
({
maxwidth: 600,
maxheight: 400,
gimmeMax: function () {
return this.maxwidth + "x" + this.maxheight;
},
init: function () {
console.log(this.gimmeMax());
}
}).init();
Here we uses parenthesis to indicate we are creating an object literal (as opposed to brackets for an iterator like for or while loop). Using object literal notation, a new object is created, but one that doesn't have prototype property. However, it is given "this" property to refer to the current object. But since it doesn't explicitly return anything, it silently returns undefined behind the scenes. So how is it then we can use dot notation to call the init() method on an object that has returned undefined?
Looks like you've created an anonymous object, and although it doesn't return anything during its construction you still have a temporary reference to it, allowing you to access it members.
So if you don't assign the result of object construction to a variable, but rather just define one anonymously, its own members temporarily available as long as you use dot notation to access them? Is this defined anywhere in ECMAScript? It seems a little awkward.
I don't have any references, but from how I've understood things the object can be self sustaining. Once all references, either done internally or externally, are lost the browser will perform garbage collection to free the memory again.
Most likely it works because init is being called on the anonymous object, and because it's being called on it, this now refers to the context of that object and since it has a method "init", that method is executed. In the first example, we didn't call init() on the object and so this referred to the global scope and since no init function declaration or expression existed in the global scope, the program stops and throws exception error "undefined". The fact that the object literal returns undefined doesn't matter since the method is being called on the object literal, which has the definition of that object in local scope.
Last edited by JohnMerlino; 01-27-2011 at 01:11 PM.
Your example where you call init3(); correctly throws an error, as it does not know where to reference that function. Unless you had a function within scope by that name, your anonymous object had already been lost at that stage:
'this' in a method means the object that had the property that is the actual method. It can be more than one object depending on the context it's called from.
Bookmarks