Using a constructor to make a list


#1



Cantact list question 4

I want to make a list but the example doesn't show how to add properties using the constructor method.
This is the sample:
var friends = {};
friends.bill = {
firstName: "Bill",
lastName: "Gates",
number: "(206) 555-5555",
address: ['One Microsoft Way','Redmond','WA','98052']
};

I wanted to use something like...


var friends = new Object() {
friends.bill.firstName = "Bill";
friends.bill.lastName = "Gates";
... and so on
}


#2

Just remove the { and }. Those are used in object literals.

var friends = new Object();

friends.bill.firstName = "...";

// and so on.

#3

var friends = new Object ();
friends.bill.firstName = "Bill";
friends.bill.lastName = "Gates";
friends.bill.number = "(206) 555-5555";
friends.bill.address = ['One Microsoft Way','Redmond','WA','98052']
friends.steve.firstName = "Steve";
friends.steve.lastName = "Jobs";
friends.steve.number = "(408) 555-5555";
friends.steve.address = ['1 Infinite Loop','Cupertino','CA','95014']

not working !


#4

We must first define friends.bill and friends.steve as objects.

friends.bill = {};
friends.steve = {};

Then your code will populate the objects.


#5

So each person has its own object within the object I think I get it...

So if I wanted to make another object within steve and within bill I could create new objects?

friends.bill.cars {};
friends.bill.cars = "BMW 325";
friends.bill.cars = "Ford Escort"


#6

To assign a value to the friends.bill.cars object it will need a property name.

friends.bill.cars.primary = ...
friends.bill.cars.secondary = ...

#7

You may find it easier to use a literal approach that is less verbose:

var friends = {
    bill: {},
    steve: {}
};

Then fill out the object literals associated with each primary key.

var friends = {
    bill: {
        firstName: "...",
        // ...
        cars: {
            primary: "...",
            secondary: "..."
        }
    },
    steve: {}
};

It really saves on typing and is very readable.