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

前端 未结 4 1349
孤街浪徒
孤街浪徒 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:13

    In the second case, the returned object doesn't inherit anything from the constructor, so there's little point in using it as such.

    > var x = new Something();
    > var y = new something2();
    > var z = something2();
    

    I.e. what will differ between x, y and z here?

    x inherits from Something, wheres neither y or z inherit from something2.

    Wouldn't something2 be a much better way of writing the constructor, since whether you use new or not will not affect the result of the function?

    There is no point in calling something2 as a constructor because the object it returns isn't the newly constructed object assigned to its this that inherits from something2.prototype, which is what others might expect to get when calling new something2().

    BTW should something2 be capitalized here? (I assume not since Crockford is so adamant on the capitalization, for functions will clobber the global namespace...)

    No, because calling it as a constructor is a bit pointless, so characterising it as one would be misleading.

提交回复
热议问题