javascript - Creating a big Object that has two methods, one of which creates a particular instance of the big Object -


i learning javascript , trying make following: create "complexnum" represents structure of complex numbers. want object have 2 methods, first 1 called "newcomplex" function needs 2 inputs: real part , imaginary parts, , returns new object complex number specified real , imaginary parts) , 1 method: norm, calculates norm.

the second method "sum" , needs 2 inputs: 2 complex numbers (as defined newcomplex), , returns object, complex number, sum of 2 previous complex numbers.

this solution:

var complexnum= {     newcomplex: function(real,img){          var z ={             partreal: real,             partimg: img,             norm: function(){                   var norm= math.sqrt(this.partimg*this.partimg + this.partreal*this.partreal );                   return norm;                    }             }          return z;     },           sum: function(a,b){             var real = a.partreal + b.partreal;             var img = a.partimg + b.partimg;             var sum = complexnum.newcomplex(real,img);             return sum;             }     } 

is better solution? 1 of questions in particular if object newcomplex sub-object of complexnum object (which objective) or if it's new object no relationship complexnum.

thank much.

to how want, complex number instance of complexnum.complex example:

var complexnum = (function() {      var complex = function complex(real, img) {          this.partreal = real;          this.partimg = img;      };      complex.prototype.norm = function() {          return math.sqrt(this.partimg * this.partimg + this.partreal * this.partreal);      }      return {          complex: complex,          newcomplex: function(real, img) {              return new complex(real, img);          },          sum: function(a, b) {              var real = a.partreal + b.partreal;              var img = a.partimg + b.partimg;              return complexnum.newcomplex(real, img);          }      }  })();  var = complexnum.newcomplex(1, 1);  var b = complexnum.newcomplex(2, 2);  console.log(a instanceof complexnum.complex);  console.log(complexnum.sum(a, b) instanceof complexnum.complex);


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -