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

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

    I'd say the most important thing would be the prototype of the returned objects.

      function Something() {
           this.foo = "bar";
      }
    
      Something.prototype = {
        // Something prototype code
        hello: function(){
         //...
        }
      }
    
      function something2() {
         var that = {};
         that.foo = "bar";
         return that;
      }
    
      something2.prototype = {
          // something2 prototype code
          greetings : function() {
          //...
          }
      }
    
      var x = new Something();
      var y = new something2();
      var z = something2();
    
      typeof x.hello === function // should be true
      typeof y.greetings === undefined // should be true
      typeof z.greetings === undefined // should be true
    

    In other words, I'd say you're not instantiating objects withe something2, you are creating purely new objects that inherit from Object.

    1. Something() will give you new objects of "Something" type when you use the new keyword.
    2. something2() will give you new objects of "Object" type, which will immediately return a new empty object.
    3. new something2 is inefficient, because you are creating a blank scope, from which you create a new object

      var that = {};
      

      which is equivalent to

      var that = new Object();
      

提交回复
热议问题