Reputation: 11438
I would like to have something like this implemented in javasript please:
var hat = new Hat(Hat.Color.RED, Hat.Size.MEDIUM);
How can I do it please (tried to mess with function prototype
but with a little success)?
Upvotes: 1
Views: 2887
Reputation: 664454
Hat
will be a constructor function:
function Hat(color, size) {
this.id = "X"+color+size; // or anything else
}
On the prototype are "methods" for Hat
instances:
Hat.prototype.raise = function() {
...
};
But the constants are properties of the Function object:
Hat.Color = {
RED: "F00",
GREEN: "0F0",
...
};
Hat.Size = {
MEDIUM: 0,
LARGE: 1,
...
};
If your library implements the "extend" function correctly (nothing special on constructors), this should also work:
Object.extend(Hat, {
Color: {RED: "F00", GREEN: "0F0", ...},
Size: = {MEDIUM: 0, LARGE: 1, ...},
});
Upvotes: 5
Reputation: 2682
This is the functional inheritance way. It distinguishes between private and publci methods and variables.
var Hat = function (color, size) {
var that = {};
that.Color = { RED: 'abc'}; // object containing all colors
that.Size = { Medium: 'big'}; // object containing all sizes
that.print = function () {
//I am a public method
};
// private methods can be defined here.
// public methods can be appended to that.
return that; // will return that i.e. all public methods and variables
}
Upvotes: 1
Reputation: 142921
You can do that if you create a Hat
constructor function like this:
function Hat(color, size) {
this.color = color;
this.size = size;
}
Hat.Color = {
RED: "#F00",
GREEN: "#0F0",
BLUE: "#00F"
};
Hat.Size = {
SMALL: 0,
MEDIUM: 1,
LARGE: 2
}
You can then create a new Hat
and get its properties
var hat = new Hat(Hat.Color.RED, Hat.Size.MEDIUM);
var hatColor = hat.color; // "#F00"
Upvotes: 6