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

前端 未结 4 1746
忘掉有多难
忘掉有多难 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: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.

提交回复
热议问题