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:

functionmyWackyConstructor() {
  returnnewDate();
}

var d = newmyWackyConstructor();
console.log(d);

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

functionmyWackyConstructor() {
  this.gotAValue = true;

  return3;
}

var v = newmyWackyConstructor();
console.log(v.gotAValue);

Typically, you should not return anything from a constructor:

functionmyNormalConstructor() {
  this.gotAValue = true;
}

var v = newmyNormalConstructor();
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

functionfoo() {
    this.x = 1;
    returnthis;
}

var aFooInstance = newfoo();

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.

functionfoo(x) {

    var _x = x;

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

var aFooInstance = newfoo(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:-

functionfoo() {
    this.x = 1;
}

var myfoo = newfoo();
console.log(myfoo.x);

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