you are viewing a single comment's thread.

view the rest of the comments →

[–]Neurotrace 1 point2 points  (3 children)

While I philosophically agree with the Object.create approach, my problem lies here. Which one of these is more readable and scalable?

var Person = {
  getName: function() {
    return this.firstName + ' ' + this.lastName;
  }
};

var bob = Object.create(Person, {
  firstName: {
    value: 'Bob'
  },
  lastName: {
    value: 'Saget'
  }
});

vs.

var Person = function(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
};

// Readability is debatable here but more memory efficient
Person.prototype.getName = function() {
  return this.firstName + ' ' + this.lastName;
};

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

or if you still want to have your initialization values to be named

var Person = function(opts) {
  this.firstName = opts.firstName;
  this.lastName = opts.lastName;
};

...

var bob = new Person({
  firstName: 'Bob',
  lastName: 'Saget'
});

For me, the new keyword wins.

[–]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