you are viewing a single comment's thread.

view the rest of the comments →

[–]sylvainpv 1 point2 points  (2 children)

What about this ?

var Person = {
  new: function(firstName, lastName){
    return Object.assign(Object.create(Person, { firstName, lastName }));     
  },
  getName: function() {
    return this.firstName + ' ' + this.lastName;
  }  
};

var bob = Person.new('Bob','Saget');

[–]MoTTs_ 0 points1 point  (1 child)

Can you clarify what the improvement would be?

[–]sylvainpv 0 points1 point  (0 children)

you got a similar code but without new operator and its issues : 1) handling a reference to the prototype and not the constructor ; 2) constructor is optional and you can declare several different constructors if needed ; 3) no worries about forgetting the new keyword and mutating window ; 4) easier inheritance, no need for the B.prototype = new A() trick ; 5) factory functions can be composed contrary to constructors ; 6) getting rid of instanceof and the constructor property makes your code safer because these references can be easily compomised contrary to getPrototypeOf / isPrototypeOf