Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good practice in Javascript to have constructor function having the same name as the object it creates?

Tags:

javascript

Let's say we have a code

function Vector ( x, y ) 
{
    this.x = x 
    this.y = y
}

var Vector = new Vector() 

Is it okay in general to have object Vector having the same name as it's constructor function?

like image 319
Alex Francis Avatar asked Mar 21 '26 06:03

Alex Francis


2 Answers

It is not a good practice to use the same name as the instanciable function, because

  • it is confusing, because you change the type of the variable from instanciable to instance,
  • it violates the good practice to name instances with starting small letters,
  • it make the instanciable function inaccessable.

To prevent confusion, you could take an IIFE as constructor.

var vector = new function (x, y) {
        this.x = x 
        this.y = y
    };

console.log(vector);
like image 182
Nina Scholz Avatar answered Mar 23 '26 20:03

Nina Scholz


Your instance shadows the constructor function. In other words, you can no longer access the constructor function after creating the instance unless you try to do it via the constructor of your Vector instance.

function Vector ( x, y ) 
{
    this.x = x 
    this.y = y
}

var Vector = new Vector() 

var AnotherVector = new Vector();   // <-Error here 

All above leads to confusion and lack of standard JS practice.

No - don't do it.

like image 30
Charlie Avatar answered Mar 23 '26 19:03

Charlie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!