Skip to content Skip to sidebar Skip to footer

What's Wrong With A Javascript Class Whose Constructor Returns A Function Or An Object

When I use new to instainciate an instance of a certain class, I got the actual instance. When the constructor function has a return value, the new sentence gives out the actual in

Solution 1:

If you return an object from a constructor, the result of the new ... expression will be the object you returned:

function myWackyConstructor() {
  return new Date();
}

var d = new myWackyConstructor();
console.log(d);

If you return a primitive, the result will be the constructed object:

function myWackyConstructor() {
  this.gotAValue = true;

  return 3;
}

var v = new myWackyConstructor();
console.log(v.gotAValue);

Typically, you should not return anything from a constructor:

function myNormalConstructor() {
  this.gotAValue = true;
}

var v = new myNormalConstructor();
console.log(v.gotAValue);

The question is, why are you returning the constructor from itself?


Solution 2:

Your code does raise an eyebrow. It does not make sense to me why you would return a static class in your constructor.

I think if you returned the actual instance it might make more sense to you but it isn't necessary.

example

function foo() {
    this.x = 1;
    return this;
}

var aFooInstance = new foo();

console.log(aFooInstance); // prints a instance of foo

However, you might want to have private variables so you can return an object like so, in this example you can also pass in the data to the constructor.

function foo(x) {

    var _x = x;

    this.getX = function(){ return _x;}      
}

var aFooInstance = new foo(1);

console.log(aFooInstance.getX()); // prints 1

I would suggest reading more on simple class instantiation.


Solution 3:

In JS, when we declare a function as a class and when we create an object of that class, that function gets called first.

Dont return from the function.


Solution 4:

The Javascript constructor does not need a return. This will work:-

function foo() {
    this.x = 1;
}

var myfoo = new foo();
console.log(myfoo.x);

Post a Comment for "What's Wrong With A Javascript Class Whose Constructor Returns A Function Or An Object"