JavaScript實現一個復數類


<script type="text/javascript">
/**
 * 這里定義Complex類,用來描述復數
 */
/**
 * 這個構造函數為它所創建的每個實例定義了實例字段r和i
 * 這兩個字段分別保存復數的實部和虛部
 * 他們是對象的狀態
 */
function Complex(real , imaginary){
    if( isNaN( real ) || isNaN( imaginary ))    //確保兩個實參都是數字
        throw new TypeError();        //如果不都是數字則拋出錯誤
    this.r = real;                     //復數的實部
    this.i = imaginary;                //復數的虛部
}

/**
 * 類的實例方法定義為原型對象的函數值屬性
 * 這里定義的方法可以被所有的實例繼承,並為他們提供共享行為
 * 需要注意的是,JavaScript的實例方法必須使用關鍵字this來存取實例的字段
 */
//當前復數對象加上另外一個復數,並返回一個新的計算和值后的復數對象
Complex.prototype.add = function(that){
    return new Complex(this.r+that.r,this.i+that.i);
};

//當前復數乘以另外一個復數,並返回一個新的計算乘積之后的復數對象
Complex.prototype.mul = function(that){
    return new Complex(this.r*that.r - this.i*that.i , this.r*that.i+this.i*that.r);
};

//計算復數的模,復數的模定義為原點(0,0)到復平面的距離
Complex.prototype.mag = function(){
    return Math.sqrt(this.r*this.r + this.i*this.i);
};

//復數的求負運算
Complex.prototype.neg = function(){
    return new Complex(-this.r , -this.i);
};

//將復數對象裝換為一個字符串
Complex.prototype.toString = function(){
    return "{"+this.r+","+this.i+"}";
};

//檢測當前復數對象是否和另一個復數相等
Complex.prototype.equals = function(that){
    return that != null &&                //必須有定義且不能是null
    that.constructor ===Complex &&         //必須是Complex的是實例
    this.r==that.r && this.i==that.i;    //必須包含相同的值
};

/**
 * 類字段(比如常量)和類方法直接定義為構造函數的屬性
 * 需要注意的是,累的方法通常不使用關鍵字this
 * 他們只對其參數進行操作
 */
//這里預定義了一些對復數運算有幫助的類字段
//他們的命名全都是大寫,用以表明他們是常量
//(在ECMAScript 5中,還能設置這些字段的屬性為只讀)
Complex.ZERO = new Complex(0,0);
Complex.ONE     = new Complex(1,0);
Complex.I      = new Complex(0,1);

//這個類方法將由實例對象的toString方法返回的字符格式解析為一個Conplex對象
//或者拋出一個類型錯誤異常
Complex.parse = function(s){
    try{
        var m = Complex._format.exec(s) ; //利用正則表達是進行匹配
        return new Complex(parseFloat(m[1]),parseFloat(m[2]));
    }catch(e){
        throw new TypeError("Can't parse '"+s+"' as a complex number.");
    }
};

//定義累的“私有”字段,這個字段在Complex.parse()中用到了下划線前綴
//來表明他是內部使用的而不屬於共有API的部分
Complex._format = /^\{([^,]+),([^}]+)\}/;

//示例代碼:
var c = new Complex(2,3);        //使用構造函數創建新的對象
var d = new Complex(2,5)    //用到了c的實例屬性
console.log(c.add(d).toString());            //“{5,5}”:使用了實例的方法
//這個稍微復雜的表達式用到了類方法和類字段
console.log(Complex.parse(c.toString()).    //將c轉換為字符串
add(c.neg()).                    //加上他的復數
equals(Complex.ZERO));            //結果應當永遠是零
</script>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM