Bill is not defined. why?


#1



ReferenceError: bill is not defined. I am trying to create the code using object constructor because i personally find it more fun to write. However is says that bill is not defined even though i made it into a new object. Can anyone help with this error. Thanks.


var friends = new Object();

friends.bill = new Object();
friends.steve = new Object();
friends.christy = new Object();

bill.firstName = "Bill";
bill.lastName = "Gates";
bill.number = "849-483-1327";

steve.firstName = "Steve";
steve.lastName = "Jobs";
steve.number = "435-712-3389";

christy.firstName = "Christy";
christy.lastName = "Freeman";
christy.number = "714-325-6689";


#2

is not the same as,

The latter is a property of the window object, which the former is a property of the friends object. Two entirely different contexts.

console.log(friends.bill.firstName);   // undefined error

Just like yours above, where bill is not defined, .firstName above is also undefined.

To write a clearer picture of context, I recommend using an object literal:

var friends = {
    bill: {

    },
    steve: {

    },
    christy: {

    }
};

This way there is only one window property, friends which is in global scope. It's members are also in the same scope, but they have a context dependency on friends.


#3

is there no way to create the same effect using object constructor?


#4

Yes there is, but it is far more verbose and less readable.

var friends = new Object();     // style guides recommend `{}`
var friends.bill = {};

friends.bill.firstName = "Bill";

and so on... The key is to keep everything in the context of friends and write the full property identifierName.


#5

Sounds great thanks!


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.