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

前端 未结 4 1738
忘掉有多难
忘掉有多难 2021-01-23 23:42

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 sen

相关标签:
4条回答
  • 2021-01-24 00:20

    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?

    0 讨论(0)
  • 2021-01-24 00:26

    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.

    0 讨论(0)
  • 2021-01-24 00:37

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

    function foo() {
        this.x = 1;
    }
    
    var myfoo = new foo();
    console.log(myfoo.x);
    
    0 讨论(0)
  • 2021-01-24 00:43

    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.

    0 讨论(0)
提交回复
热议问题