When you think about objects in Javascript, simply think about hash tables of key-value pairs (similar to what are called “associative arrays” in other languages). The values can be primitives or other objects; in both cases they are called properties. The values can also be functions, in which case they are called methods.
The custom objects you create in Javascript (in other words, the user-defined native objects) are mutable at any time. Many of the properties of the built-in native objects are also mutable. You can start with a blank object and add functionality to it as you go. The object literal notation is ideal for this type of on-demand object creation.
Consider the following example:
// start with an empty object
var dog = {};
// add one property
dog.name = "Benji";
// now add a method
dog.getName = function () {
return dog.name;
};In the preceding example, you begin with a clean slate—a blank object. Then you add a property and a method to it. At any time in the life of the program you can:
- Change the values of properties and methods, for example:
dog.getName = function () { // redefine the method to return // a hardcoded value return "Fido"; };
- Remove properties/methods completely:
delete dog.name;
- Add more properties and methods:
dog.say = function () { return "Woof!"; }; dog.fleas = true;
You are not required to start with an empty object. The object literal pattern enables you to add functionality to the object at the time of creation, as the next example demonstrates.
var dog = {
name: "Benji",
getName: function () {
return this.name;
}
};Note: You'll see “blank object” and “empty object” in a few places throughout this book. It’s important to understand that this is for simplicity and there’s no such thing as an empty object in Javascript. Even the simplest
{} object already has properties and methods inherited from Object.prototype. By “empty” we’ll understand an object that has no own properties other than the inherited ones.The Object Literal Syntax
If you’re not used to the object literal notation, it may look a little odd at the beginning, but the more you use it, the more you’ll love it. In essence, the syntax rules are:
- Wrap the object in curly braces (
{and}).
- Comma-delimit the properties and methods inside the object. A trailing comma after the last name-value pair is allowed but produces errors in IE, so don’t use it.
- Separate property names and property values with a colon.
- When you assign the object to a variable, don’t forget the semicolon after the closing }.
Objects from a Constructor
There are no classes in Javascript and this allows for great flexibility, because you don’t have to know anything about your object in advance; you don’t need a class “blueprint.” But Javascript also has constructor functions, which use syntax similar to the class-based object creation in Java or other languages.
You can create objects using your own constructor functions or using some of the built-in constructors such as
Object(), Date(), String() and so on.Here’s an example showing two equivalent ways to create two identical objects:
// one way -- using a literal
var car = {goes: "far"};
// another way -- using a built-in constructor
// warning: this is an antipattern
var car = new Object();
car.goes = "far";As you can see from this example, an obvious benefit of the literal notation is that it’s shorter to type. Another reason why the literal is the preferred pattern for object creation is that it emphasizes that objects are simply mutable hashes and not something that needs to be baked from a “recipe” (from a class).
Another reason for using literals as opposed to the
Object constructor is that there is no scope resolution. Because it’s possible that you have created a local constructor with the same name, the interpreter needs to look up the scope chain from the place you are calling Object() all the way up until it finds the global Object constructor.Object Constructor Catch
You have no reason to use the
new Object() constructor when you can use an object literal, but you might be inheriting legacy code written by others, so you should be aware of one “feature” of this constructor (or yet another reason not to use it). The feature in question is that the Object() constructor accepts a parameter and, depending on the value passed, it may decide to delegate the object creation to another built-in constructor and return a different object than you expect.Following are a few examples of passing a number, a string, and a boolean value to
new Object(); the result is that you get objects created with a different constructor:// Warning: antipatterns ahead
// an empty object
var o = new Object();
console.log(o.constructor === Object); // true
// a number object
var o = new Object(1);
console.log(o.constructor === Number); // true
console.log(o.toFixed(2)); // "1.00"
// a string object
var o = new Object("I am a string");
console.log(o.constructor === String); // true
// normal objects don't have a substring()
// method but string objects do
console.log(typeof o.substring); // "function"
// a boolean object
var o = new Object(true);
console.log(o.constructor === Boolean); // trueThis behavior of the
Object() constructor can lead to unexpected results when the value you pass to it is dynamic and not known until runtime. Again, in conclusion, don’t use new Object(); use the simpler and reliable object literal instead.What's the best approach for developing an application with Javascript? This book helps you answer that question with numerous Javascript coding patterns and best practices. If you're an experienced developer looking to solve problems related to objects, functions, inheritance, and other language-specific categories, the abstractions and code templates in this guide are ideal -- whether you're writing a client-side, server-side, or desktop application with Javascript. Author Stoyan Stefanov includes several examples for each pattern as well as practical advice for implementing them.




Help






