Coding patterns for initializing objects - constructors (new) vs. Object.create() (Crockford)

后端 未结 1 1310
滥情空心
滥情空心 2021-02-10 13:32

Note: This is not a question about classical and prototype inheritance. It\'s about what coding patterns to use to initialize objects. Class constructors create and initiali

1条回答
  •  庸人自扰
    2021-02-10 14:22

    Instead of having:

    function Person(first, last) {
      this.name = {
        first: first,
        last: last
      };
    }
    
    Person.prototype.tellName = function() {
      return this.name.first + ' ' + this.name.last;
    }
    

    You'd just have:

    function Person(first, last) {
      return {
        name: { first: first, last: last },
        tellName: function() { return this.name.first + ' ' + this.name.last; }
      };
    };
    

    Or, if you prefer how person.create() looks, then:

    var person = {
      create: function(first, last) {
        return {
          name: { first: first, last: last },
          tellName: function() { return this.name.first + ' ' + this.name.last; }
        };
      }
    };
    

    But in the second case you'd have an unnecessary object (person) containing only one function (person.create()).

    No need for Object.create nor new since those are for inheritance which you said you do not care about. This would let you do:

    var p1 = Person('John', 'Doe');
    var p2 = Person('Sven', 'Svensson');
    

    A fun fact is that you can still use new in front of person.create this way if you want but it would offer no effect. If you have to use the existing function you can set the this context explicitly by using .call

    // with your original `Person`
    var p1 = Person.call({}, 'John', 'Doe');
    var p2 = Person.call({}, 'Sven', 'Svensson');
    

    This would not set the prototype either since the function is not called like a constructor. See this answer about what prototypical answer does and doesn't do - in a line it's about sharing functionality it's not about constructing properties of your objects.

    0 讨论(0)
提交回复
热议问题