Werner Germán Busch Werner Germán Busch - 1 month ago 14
Javascript Question

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

I am learning javascript and I was trying to make the following: create a "complexNum" which represents the structure of complex numbers. I want that object to have two methods, the first one is called "newComplex" which is a function that needs two inputs: real part and imaginary parts, and returns a new object which is a complex number with the specified real and imaginary parts) and one method: the norm, which calculates the norm.

The second method is "sum" and needs two inputs: two complex numbers (as defined by newComplex), and returns another object, a complex number, which is the sum of the two previous complex numbers.

This is my 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 this the better solution? One of my questions in particular is if the object newComplex is actually a sub-object of the complexNum object (which is my objective) or if it's a completely new object with no relationship with complexNum.

Thank you very much.

Answer Source

To get it how you want, so that a complex number is an instance of complexNum.Complex for 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 a = 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);