What difference is there in JavaScript between a constructor function, and function returning object which is invoked as a constructor?

前端 未结 4 1347
孤街浪徒
孤街浪徒 2020-12-14 04:26

I know this is not the recommended way of doing it, but if I declare the following functions, and then invoke them as constructors, what will be the difference (if any) betw

4条回答
  •  清歌不尽
    2020-12-14 05:20

    Invoking a function as a constructor (i.e. with the new keyword) runs the following steps:

    1. create a new object
    2. set the prototype of that object to the object in the prototype property of the function
    3. execute the constructor function in the context of that object (i.e. this is the new object)
    4. return that object (if the constructor has no return statement)

    So, your second solution will just return a plain object with a property "foo". But neither y nor z are instanceof Something2 and don't inherit from that prototype. There are functions like that, yes, but they should not be called constructors (no uppercase naming, no invokation with new). They belong to the factory pattern.

    If you want a constructor which can be executed without new, use that code:

    function Something(params) {
        if (! this instanceof Something)
             return new Something(params);
        // else use "this" as usual
        this.foo = "bar";
        ...
     }
    

提交回复
热议问题