使Rational类能够处理数学运算符

Xla*_*ius 5 javascript dsl operator-overloading fractions prototypal-inheritance

我有这个Rational类,每个操作都有一个方法(add,mult等)

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
Run Code Online (Sandbox Code Playgroud)

我可以让它更"自然",例如启用console.log( a * b )吗?

eme*_*esx 9

你不能重载运算符(阅读类似的问题).

此外,类似的专用方法mult可以被视为良好设计的标志(不仅仅是在Javascript中),因为改变原始操作符行为会使用户感到困惑(好吧,理性数字实际上是一个很好的重载候选者).

您可以更改printtoString为用户thg435已建议.

更进一步:

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

这将启用a * b语法(注意:您不再操作Rationals,而是基于原语).

  • 我特意问了一个[问题](http://stackoverflow.com/questions/17108265/make-toprimitive-conversion-depend-on-the-context)这个问题. (2认同)