Matt Kelly
Matt Kelly

Reputation: 1491

Javascript - Undefined object in an object

I know there are a lot of similar questions to this one, and I've looked through quite a few but haven't managed to find my answer.

I have created a custom object called destination:

function destination() {
    var city = "";
    var flightNumber = "";
    var type = "";
}

I have then created a second custom object, and one of the properties of that object is of type destination:

function plane() {
    var flightNumber = "";
    var otherCity = new destination();
    var status = "";
    var taxiRoute = [];
    var airRoute = "";
    var heading = 0;
    var speed = 0;
    var left = 0;
    var top = 0;
    var height = 0;
    var width = 0;
    var dx = 0;
    var dy = 0;
}

However, whenever I try to access any of the properties of type destination using something like:

aPlanes[0].otherCity.city;

where aPlanes is an array of plane() objects, I get the undefined error message in the browser console:

Uncaught TypeError: Cannot read property 'city' of undefined

Is anyone able to point out where I'm going wrong? It's driving me mad!

Thanks in advance.

Upvotes: 1

Views: 688

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386776

You have a wrong class definition. You need this and not local variables with var declaration.

function Destination() {
    this.city = "";
    this.flightNumber = "";
    this.type = "";
}

BTW, I suggest to use the standard for class declarations with upper case first letter.

Upvotes: 3

Related Questions