In practice, you’ll probably see option 1 used often. Option 2 is really a bad practice and you shouldn’t use it (I’m not sure if I can remember seeing option 2 used in the real world…). Option 3 is only available if your runtime is compatible with ECMAScript5 (I’ll return to it in a future post). Notice that all of these options produce the same result: an empty object.
Once again, the previous instructions end up generating similar results. In both cases, you’ll end up with an object that has a name property and whose value is set to Luis. If you’re creating a new object with the literal syntax, then you can do it all at once:
By now, you’ve probably noticed why the literal syntax is used so often. There’s still an alternative way of creating properties which is more powerful, but only compatible with ECMAScript5 (we’ll leave it for a future post). Going back to object creation, there’s still a final approach: we can create a function and use it as a “constructor”. A function is “transformed” into a “constructor” when it’s prefixed with the new keyword during its invocation. Here’s a quick example of how you can build a simple object by using a constructor:
In this case, you’ll also end up with an object which has a single property name, whose value is also set to Luis. Even thought the results are similar, there are some important differences between the objects created. For instance, if you check the constructor property, you’ll notice that p returns a reference to Person while obj1 returns a reference to Object. As we’ll see, this difference might be important, but for now, we don’t have to worry about it because we’re simply interested in creating objects.
And that’s it for now. Stay tuned for more.
PS: does anyone have any suggestion on how to format the code before pasting it in Windows Live Writer? I’m using code snippet for now, but I’d prefer to have a dark scheme for my code…