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

前端 未结 4 1770
忘掉有多难
忘掉有多难 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?

提交回复
热议问题