/ Javascript

Passing Objects as Argument to Class - JavaScript

Few days back, I struggled with a very small concept in JavaScript that required to pass an object of the same class as an argument to it. In doing so, I faced a very genuine issue on how one can pass the object as argument where as the argument is expecting a variable to initiate the respective object. I searched heavily on the Internet and couldn't find a proper solution. So I thought of writing my own method.

The task is pretty simple, need to create a class in Javascript which when instantiated can take in variables as well as objects of the same class.
To simplify, let me give you an example.

Suppose I have a class name defined as Point which simply initializes X and Y axis coordinates. Therefore, the call that I was looking to satisfy was :-

The function getPoints simply prints out the value of the x and y.
Lets start building the class.

There we are. We have the class built and it simply initializes the object via this.
Now we need to implement the feature that says, if the passed arguments are of type Object, add their x and y points and pass it to the class variables. So getPoints can print those points. Now this is my approach and this may not be the best, but it worked for me.

I simply checked if the type of the arguments passed is object type or not. If it is of type object, handle differently and pass on the value.
So if I put the following in the console -

var p = new Point(new Point(10,13), new Point(12,14));
var q = new Point(12,23);

The Output is -


Any suggestions are most welcome. Again. this may not be the best approach but It worked for me. Do comment.