JavaScript實現以個複數類

來源:互聯網
上載者:User

標籤:blog   出錯   屬性   參數   number   大寫   null   tostring   prot   

<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>

 

JavaScript實現以個複數類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.