Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have this Rational class that has a method for each operation (add,mult etc)

function Rational(nominator, denominator){
    this.nominator = nominator;
    this.denominator = denominator || 1;    
}

Rational.prototype = {
    mult: function(that) {
        return new Rational(
            this.nominator * that.nominator,
            this.denominator * that.denominator
            );
    },
    print: function() {
        return this.nominator + '/' + this.denominator;
    }
};

var a = new Rational(1,2),
    b = new Rational(3);

console.log( a.mult(b).print() ); // 3/2

Can I make it more "natural" e.g. to enable console.log( a * b ) ?

share|improve this question
3  
Javascript doesn't support operator overloading. You can replace print() with toString though. – thg435 10 mins ago

2 Answers

You can't overload operators (read similar questions).

Moreover, a dedicated method like mult can be treated as a sign of good design (not only in Javascript), since changing the original operator behavior can confuse users (well, a rational number actually a good candidate for overloading).

You can change print to toString as user thg435 has suggested.

Going even further:

Rational.prototype = {
    mult : ... ,
    toString: ... ,
    valueOf: function() { return this.nominator / this.denominator; }
};

this will enable the a * b syntax (note: you don't operate on Rationals any more, but rather on primitives).

share

Javascript doesn't support operator overloading. However, it does provide "magic methods" toString and valueOf that are used to get a "primitive" value of an object in string and numeric contexts respectively. This allows for some simplifications in your code:

Rational.prototype.toString = function() {
    return this.nominator + '/' + this.denominator;
}
Rational.prototype.valueOf = function() {
    return this.nominator / this.denominator;
}

console.log("Result=" + a.mult(b)); // Result=1.5
console.log(a * b); // 1.5

Note that the last 1.5 is not a Rational object anymore, but rather the primitive value (number).

share

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.