Creating new objects
You can create an object using an object initializer. Alternatively, you can first create a constructor function and then instantiate an object by invoking that function with the new operator.
Using object initializers
Object initializers are also called object literals. "Object initializer" is consistent with the terminology used by C++.
The syntax for an object using an object initializer is:
const obj = {
property1: value1, // property name may be an identifier
2: value2, // or a number
"property n": value3, // or a string
};
Each property name before the colon is either an identifier, a number literal, or a string literal, and each valueN is an expression whose value is assigned to the property name. The property name can also be an expression; computed keys need to be wrapped in square brackets. The object initializer reference contains a more detailed explanation of the syntax.
In this example, the newly created object is assigned to a variable obj — this is optional. If you do not need to refer to this object elsewhere, you do not need to assign it to a variable. (Note that you may need to wrap the object literal in parentheses if the object appears where a statement is expected, so as not to have the literal be confused with a block statement.)
Object initializers are expressions, and each object initializer results in a new object being created whenever the statement in which it appears is executed. Identical object initializers create distinct objects that do not compare to each other as equal.
The following statement creates an object and assigns it to the variable x if and only if the expression cond is true:
let x;
if (cond) {
x = { greeting: "hi there" };
}
The following example creates myHonda with three properties. Note that the engine property is also an object with its own properties.
const myHonda = {
color: "red",
wheels: 4,
engine: { cylinders: 4, size: 2.2 },
};
Objects created with initializers are called plain objects, because they are instances of Object, but not any other object type. Some object types have special initializer syntaxes — for example, array initializers and regex literals.
Using a constructor function
Alternatively, you can create an object with these two steps:
- Define the object type by writing a constructor function. There is a strong convention, with good reason, to use a capital initial letter.
- Create an instance of the object with
new.
To define an object type, create a function for the object type that specifies its name, properties, and methods. For example, suppose you want to create an object type for cars. You want this type of object to be called Car, and you want it to have properties for make, model, and year. To do this, you would write the following function:
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
Notice the use of this to assign values to the object's properties based on the values passed to the function.
Now you can create an object called myCar as follows:
const myCar = new Car("Eagle", "Talon TSi", 1993);
This statement creates myCar and assigns it the specified values for its properties. Then the value of myCar.make is the string "Eagle", myCar.model is the string "Talon TSi", myCar.year is the integer 1993, and so on. The order of arguments and parameters should be the same.
You can create any number of Car objects by calls to new. For example,
const randCar = new Car("Nissan", "300ZX", 1992);
const kenCar = new Car("Mazda", "Miata", 1990);
An object can have a property that is itself another object. For example, suppose you define an object called Person as follows:
function Person(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
and then instantiate two new Person objects as follows:
const rand = new Person("Rand McKinnon", 33, "M");
const ken = new Person("Ken Jones", 39, "M");
Then, you can rewrite the definition of Car to include an owner property that takes a Person object, as follows:
function Car(make, model, year, owner) {
this.make = make;
this.model = model;
this.year = year;
this.owner = owner;
}
To instantiate the new objects, you then use the following:
const car1 = new Car("Eagle", "Talon TSi", 1993, rand);
const car2 = new Car("Nissan", "300ZX", 1992, ken);
Notice that instead of passing a literal string or integer value when creating the new objects, the above statements pass the objects rand and ken as the arguments for the owners. Then if you want to find out the name of the owner of car2, you can access the following property:
car2.owner.name;
You can always add a property to a previously defined object. For example, the statement
car1.color = "black";
adds a property color to car1, and assigns it a value of "black". However, this does not affect any other objects. To add the new property to all objects of the same type, you have to add the property to the definition of the Car object type.
You can also use the class syntax instead of the function syntax to define a constructor function. For more information, see the class guide.
Using the Object.create() method
Objects can also be created using the Object.create() method. This method can be very useful, because it allows you to choose the prototype object for the object you want to create, without having to define a constructor function.
// Animal properties and method encapsulation
const animalProto = {
type: "Invertebrates", // Default value of properties
displayType() {
// Method which will display the type of animal
console.log(this.type);
},
};
// Create a new animal type called `animal`
const animal = Object.create(animalProto);
animal.displayType(); // Logs: Invertebrates
// Create a new animal type called fish
const fish = Object.create(animalProto);
fish.type = "Fishes";
fish.displayType(); // Logs: Fishes