samedi 22 octobre 2016

JavaScript - Dynamic Prototype Pattern + Parasitic Combination Inheritance

I am working through Professional JavaScript for Web Developers, and have a question regarding Object Creation and Inheritance. In the book, the Dynamic Prototype Pattern is discussed as a nice way of doing Combination Constructor/Prototype pattern while keeping the constructor and prototype encapsulated to the Object definition. Like this:

function Person(name, age, job) {
  this.name = name;
  this.age = age;
  this.job = job;

  if (typeof this.sayName != "function") {
    Person.prototype.sayName = function () {
      return this.name;
    };
  }
}

Of all the Object Creation patterns discussed in the book, I felt like this one looked the best. Then when discussing inheritance, the book says Parasitic Combination Inheritance is considered the optimal inheritance paradigm. As follows:

function inheritPrototype(subType, superType) {
  var prototype = Object(superType.prototype);
  prototype.constructor = subType;
  subType.prototype = prototype;
}

function SuperType(name) {
  this.name = name;
  this.colors = ['red', 'blue', 'green'];
}

SuperType.prototype.sayName = function() {
  return this.name;
};

function SubType(name, age) {
  SuperType.call(this, name);
  this.age = age;
}

inheritPrototype(SubType, SuperType);

SubType.prototype.sayAge = function() {
  return this.age;
}

As you can see, this code uses the Combination Constructor/Prototype Pattern for creating objects, where the prototypes are declared outside of the original object creation. My question is, is there any issue with combining the Dynamic Prototype Pattern with Parasitic Combination Inheritance, like this:

function inheritPrototype(subType, superType){
  var prototype = Object(superType.prototype);
  prototype.constructor = subType;
  subType.prototype = prototype;
}

function SuperType(name) {
  this.name = name;
  this.colors = ['red', 'blue', 'green'];

  if (typeof this.sayName != "function") {
    SuperType.prototype.sayName = function() {
        return this.name;
    };
  }
}

function SubType(name, age) {
  SuperType.call(this, name);
  this.age = age;

  if (typeof this.sayAge != "function") {
    SubType.prototype.sayAge = function() {
        return this.age;
    };
  }
}

inheritPrototype(SubType, SuperType);

I've tested this in a jsfiddle here and it seems to work fine, I just wanted to make sure there isn't something I'm missing that will cause problems later using this pattern/inheritance.

Also, as I know this book is a little older, are there new standards for object creation and inheritance?

Aucun commentaire:

Enregistrer un commentaire