Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you create an object in Javascript without declaring every value, and how?

I want to do the following:

var Room = function(name, north, south, east, west) {
    this.name = name;
    this.north = north;
    this.south = south;
    this.west = west;
    this.east = east;
}

Where north, south, east and west is just a flag saying if there is a door there.

When I create an object I have to do this:

var bedroom = new Room('Bedroom', true, false, false, false);

I was wondering if there is a way so that I can just say which directions have a true value such as:

var bedroom = new Room({
    name: 'Bedroom',
    north: true
});

With south, east, and west becoming false. This way if I were to have say 20 different options I would only have to specify the ones I care about, instead of having a long declarations with a lot of false and '' values and I wouldn't need to remember which order they were suppose to be in (north, south, east, west? or north, east, south, west?),

like image 788
Jonathan Owen Chute Avatar asked Sep 06 '25 07:09

Jonathan Owen Chute


1 Answers

If you really need separate instance variables for north, south, east and west, I'd suggest something like this where you can pass just the directions that you care about in a space delimited string. This makes the calling code much simpler since you don't have to pass anything for the directions that don't exist.

var Room = function(name, directions) {
    this.name = name;
    this.north = this.south = this.west = this.east = false;
    directions = directions.split(" ");
    directions.forEach(function(item) {
        this[item] = true;
    })
}

var bedroom = new Room('Bedroom', 'north south');

Or, your object approach works fine too:

var Room = function(name, directions) {
    this.name = name;
    this.north = this.south = this.west = this.east = false;
    for (var dir in directions) {
        this[dir] = directions[dir];
    }
}

var bedroom = new Room('Bedroom', {north: true, south: true});

A third approach is to use flags (often used in C/C++). This allows you to pass an arbitrary number of flags in a single value:

var Room = function(name, directions) {
    this.name = name;
    this.directions = directions;
}

Room.prototype = {
   isNorth: function() { return this.directions & Room.north},
   isSouth: function() { return this.directions & Room.south},
   isWest: function() { return this.directions & Room.west},
   isEast: function() { return this.directions & Room.east},
};

Room.north = 1;
Room.south = 2;
Room.east = 4;
Room.west = 8;

var bedroom = new Room('Bedroom', Room.north | Room.south);
like image 88
jfriend00 Avatar answered Sep 08 '25 20:09

jfriend00