Reputation: 31
I saw a solution from Stijn de Witt for definine enums in Javascript.
var SIZE = {
SMALL : {value: 0, name: "Small", code: "S"},
MEDIUM: {value: 1, name: "Medium", code: "M"},
LARGE : {value: 2, name: "Large", code: "L"}
};
Usage:
alert(SIZE.SMALL.value);
...
I have been trying to adapt this to allow me to define Users.
var RRR : {name: "RRRaney:, number: 2, date: 2007};
This works as I would expect:
alert(RRR.name + " " + RRR.date); //to display the text "RRRaney 2007".
I would like to try to define the .name as the default, so I could write something like:
alert(RRR + " " + RRR.date); //to display the text "RRRaney 2007".
or just
alert(RRR); // to display the text "RRRaney".
Upvotes: 2
Views: 475
Reputation: 78650
Well this might be a bad idea and I have no idea how other browsers will handle this, but this works in chrome...
var RRR = {
name: "RRRaney",
number: 2, date: 2007,
toString: function(){
return this.name;
}
};
alert(RRR + " " + RRR.date);
Didn't think this would actually work, so chances are it won't in other browsers.
Upvotes: 3
Reputation: 13907
I am not sure if I should write this, since it is in the same spirit of kingjiv's answer. But it is slightly different, so I decided to put it here in any case.
function enum(name, value, date) {
this.name = name;
this.value = value;
this.date = date;
}
enum.prototype.toString = function() {
return this.name;
}
Usage is:
RRR = new enum("RRRaney", 2, 2007);
alert(RRR + " " + RRR.date);
Edit: An unfortunate choice of object name. Apparently enum
is a reserved keyword in javascript 1.3+, so the code fails in internet explorer. You need to rename it to Enum
or some such if you want to use it.
Upvotes: 0
Reputation: 322492
The only way I can think of would be hackish and undesirable, but here it goes:
var RRR = new String("RRRaney:");
RRR.date = "2007";
alert( RRR + RRR.date );
Instead of using a string literal for your name
, this is borrowing a String wrapper object to be your object with a value of "RRRaney:"
, and adding a date
property to that wrapper object.
It gives the result you want, but seriously, don't do it. Just stick with a typical object literal.
You mentioned prototype
in the title of your question.
If you were thinking of a Constructor function that gives a default name
for the objects it creates, that's a different story:
var MyConstructor = function( date ) {
this.date = date;
};
MyConstructor.prototype.name = "RRRaney:";
var inst = new MyConstructor( "2007" );
But it doesn't represent RRR
in the manner you want.
Upvotes: 1