What's wrong with a JavaScript class whose constructor returns a function or object

When I use new to install an instance of a specific class, I got the actual instance. When the constructor function has a return value, the new clause also returns the actual instance. However, when the constructor returns by itself, I cannot get the instance. Instead, I get a constructor. I wander what's wrong with that.

Here is my code snippet:

 function foo() { this.x = 1; return foo; } console.log(new foo()); // prints the defination of foo 

As we believe, in most situations it makes no sense to return such a function. However, why does JS have such a feature? Is there any consideration when designing JS? Or is it just a JS bug?

+1
source share
4 answers

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

 function myWackyConstructor() { return new Date(); } var d = new myWackyConstructor(); console.log(d); 

If you return the primitive, the result is a constructed object:

 function myWackyConstructor() { this.gotAValue = true; return 3; } var v = new myWackyConstructor(); console.log(v.gotAValue); 

Generally, you should not return anything from the constructor:

 function myNormalConstructor() { this.gotAValue = true; } var v = new myNormalConstructor(); console.log(v.gotAValue); 

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

+3
source

Your code raises an eyebrow. It makes no sense to me why you are returning a static class to your constructor.

I think that if you return the actual instance, this may make more sense to you, but it is not 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 that you can return such an object, in this example you can also pass 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 about a simple instance of a class .

+1
source

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

Do not return from function.

0
source

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

 function foo() { this.x = 1; } var myfoo = new foo(); console.log(myfoo.x); 
0
source

Source: https://habr.com/ru/post/1244131/


All Articles