Subj : Re: defining operators for custom classes (SpiderMonkey) To : netscape.public.mozilla.jseng From : zwetan Date : Tue Oct 12 2004 04:11 pm > Is it possible to do 'operator overloading' for custom classes in > SpiderMonkey? > > I.E.: > -------------------------------- > var objA = new MyObject(); // custom class backed by native source > var objB = new MyObject(); > > var objC = objA + objB; // call some native source function to > calcualte the result > --------------------------------- > > Looks alot better than > > var objC = objA.Plus(objB); > nope, but you can fake it in certain ways overloading the valueOf method and returning a primitive (sorry if the answer sound off topic, meaning not related to js engine) MyObject.prototype.valueOf = function() { return this._value; /*Number*/ } and then you could something as var objC = new MyObject( objA + objB ); provided that your constructor accept the primitive type as argument MyObject= function( /*Number*/ value ) { this._value = value; } concrete exemple: a Version constructor instead of doing that: Version = function( /*Int*/ major, /*Int*/ minor, /*Int*/ build, /*Int*/ revision ) { this.major = major; this.minor = minor; this.build = build; this.revision = revision; } you re doing this: Version = function( /*Int*/ major, /*Int*/ minor, /*Int*/ build, /*Int*/ revision ) { this._value = major << 24 | minor << 20 | build << 8 | revision; } then: Version.prototype.valueOf = function() { return this._value; } this allow you to use operator directly on the custom object: test1 = new Version(1,0,0,0); test2 = new Version(1,0,2,0); if( test1 < test2 ) { //code here } and if you want to add two or more Version object modify the constructor: Version = function( /*Int*/ major, /*Int*/ minor, /*Int*/ build, /*Int*/ revision ) { if( arguments.length == 1 ) { this._value = arguments[0]; } else { this._value = major << 24 | minor << 20 | build << 8 | revision; } } test3 = new Version( test1 + test2 ); // v2.0.2.0 HTH zwetan note: this is just simple exemple not solid code ;) .