Last active
August 29, 2015 14:05
-
-
Save KC-Liu/a62bdaac1b361872145d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
implement complex mathamatic property using JS Object | |
*/ | |
// Define constructor : =================================================================== | |
// ( c = x + y i ) | |
// ======================================================================================== | |
function Complex(real,imaginary){ | |
this.x = real; | |
this.y = imaginary; | |
} | |
// Define instance property: ============================================================= | |
// (check "Complex.prototype" as well) | |
// ======================================================================================== | |
// the distance from (0,0) = x^2+y^2 | |
Complex.prototype.magnitude = function(){ | |
return Math.sqrt(this.x*this.x + this.y*this.y); | |
} | |
// -c = - ( x + y i ) | |
Complex.prototype.negative = function(){ | |
return new Complex(-this.x,-this.y); | |
} | |
// overwrite toString method | |
Complex.prototype.toString = function(){ | |
return "(" + this.x + "," + this.y + ")"; | |
} | |
// real(x) as the basic value | |
Complex.prototype.valueOf = function(){ return this.x ;} | |
// Define class property: =============================================================== | |
// (check "Complex.hasOwnProperty('{prperty name}')" as well) | |
// ======================================================================================== | |
// c1+c2 = ( x1+x2 , y1+y2 ) | |
Complex.add = function(a,b){ | |
return new Complex( a.x + b.x , a.y + b.y ); | |
} | |
// c1-c2 = ( x1-x2 , y1-y2 ) | |
Complex.subtract = function(a,b){ | |
return new Complex( a.x - b.x , a.y - b.y ); | |
} | |
// c1*c2 = ( x1*x2 , y1*y2 ) | |
Complex.multiply = function(a,b){ | |
return new Complex( a.x * b.x , a.y * b.y ); | |
} | |
// define 0,1,i as class property | |
Complex.zero = new Complex(0,0); | |
Complex.one = new Complex(1,0); | |
Complex.i = new Complex(0,1); | |
// Evaluattion ( not neccesary) ============================================================= | |
console.log(Complex.prototype); | |
var c1 = new Complex(-1,3); | |
var c2 = new Complex(2,0.5); | |
c1.magnitude(); | |
Complex.add(c1,c2); | |
Complex.subtract(c2,Complex.i); | |
// Plus ===================================================================================== | |
c1.constructor == Complex; //true | |
c1.constructor == Object; //false | |
Complex.prototype.isPrototypeOf(c1); // true | |
Object.prototype.isPrototypeOf(c1); // true | |
c1 instanceof Complex; // true | |
c1 instanceof Object; // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment