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?),
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With