1

I'm getting the following error when trying to create a nested object using a constructor:

Uncaught TypeError: Cannot read property 'data' of undefined

Here's my code:

function Car(name){
    this.name.data.CarName = name;
    this.show = function(){document.getElementById("fill").innerHTML = toyota.name.data.CarName;};
}
var toyota;
function functionadd(){
    toyota = new Car("Toyota");
    toyota.show();
}

I have looked this up everywhere and can't seem to find an answer and am wondering if I'm making some stupid mistake. Any help is fantastic, thanks :)

1 Answer 1

1

It's because object name is undefined and there is also no property data on it, so you have to initialize this.name and this.name.data before adding CarName:

function Car(name){
    this.name = {};
    this.name.data = {};
    this.name.data.CarName = name;
    this.show = function(){document.getElementById("fill").innerHTML = toyota.name.data.CarName;};
}

It's shorter with object litteral:

function Car(name){
    this.name = { data: { CarName: name } };
    this.show = function(){document.getElementById("fill").innerHTML = toyota.name.data.CarName;};
}
Sign up to request clarification or add additional context in comments.

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.