0

I am working on a project and currently learning Javascript. Right now, I am wondering how I can create an object with a constructor, assign attributes to it, and later read and modify these attributes. I think I got the creation and the assigning part right, but I can't seem to access any of my object's attributes from the outside.

function initialize() { 
    var testPlane = jet("9C3476", currentAirport, "Palma De Mallorca", "02:45", "Departed");

    alert("Never get to this point: " + testPlane.id);
}


function jet(id, from, to, expected, status) {
    this.id = id;
    this.from = from;
    this.to = to;
    this.expected = expected;
    this.status = status;
    this.position = from;
    alert("Id: "+ id + " From:" + from + " To: " + to + " Expected: " + expected + " Status: " + status);
    this.marker = new google.maps.Marker({
      position : this.position,
      icon : img,
      map : map,
    });
}

2 Answers 2

2

Check your browser console:

TypeError: Cannot read property 'id' of undefined

Use new to treat jet as a constructor:

var testPlane = new jet("9C3476", currentAirport, "Palma De Mallorca", "02:45", "Departed");

Without new, the code assigns whatever value jet() returns to testPlane, but since jet does not return anything at all, testPlane is undefined.

Sign up to request clarification or add additional context in comments.

Comments

0

If you want to use the function "jet" as constructor, you need to call it with "new" as -

var testPlane = new jet("9C3476", currentAirport, "Palma De Mallorca", "02:45", "Departed");

OR

put this line inside function "jet" -

if(!(this instanceof jet)) {
    return new jet("9C3476", currentAirport, "Palma De Mallorca", "02:45", "Departed");
}

Also.. i hope "currentAirport", "google" are defined in your code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.