Reputation: 13
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 :)
Upvotes: 1
Views: 37
Reputation: 13356
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;};
}
Upvotes: 1