lephleg
lephleg

Reputation: 1764

JavaScript - Composite objects with object properties

I want to create a composite object (eg device) which would have other objects as a properties (eg position). Is this possible to achieve in JavaScript by using constructors?

var pos = new position(23,10,15);
var dev = new device(01,"mobile",pos);

//device obj constructor   
function device(id, type, position) {
   this.id=id;
   this.type=type;
   this.position = {position.lat, position.lon, position.alt};
}

//position obj constructor
function position(lat,lon,alt) {
   this.lat=lat;
   this.lon=lon;
   this.alt=alt;
}

I'm getting error "SyntaxError: Unexpected token ."

Upvotes: 0

Views: 1248

Answers (2)

anonymous
anonymous

Reputation: 1532

Yes it is possible. You are getting SyntaxError, because you have a syntax error. You can nest objects like this:

device = {
    id: 43,
    type: 34,
    position: { 
       lat: 2,
       lon: 4,
       alt: 343 
       }
    };

Your function should look like this if you want to assign the whole object to the variable:

function device(id, type, position) {
    this.id=id;
    this.type=type;
    this.position = position;
}

However if you want to assign just some of the variables of the object, you should do it like this:

function device(id, type, position) {
    this.id=id;
    this.type=type;
    this.position = {
        alt: position.alt,
        lon: position.lon,
        lat: position.alt
    };
}

Upvotes: 2

alsafoo
alsafoo

Reputation: 788

replace this line

this.position = {position.lat, position.lon, position.alt};

with this

this.position = position

Upvotes: 1

Related Questions