Examples
Object type and object instance
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; }
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.year
is the integer 1993, and so on.
You can create any number of car
objects by calls to new
. For
example:
const kensCar = new Car('Nissan', '300ZX', 1992);
Object property that is itself another object
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 McNally', 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);
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
parameters for the owners. To find out the name of the owner of car2
, you
can access the following property:
car2.owner.name
Using new
with classes
class Person { constructor(name) { this.name = name; } greet() {
console.log(`Hello, my name is ${this.name}`); } } const p = new Person("Caroline"); p.greet(); // Hello, my name is Caroline