Subclasses in mixin patterns missunderstanding

19 views Asked by At

I have a question about Addy Osmani's subclasses explanation in mixin pattern.

Here is a source code:

var Person = function( firstName, lastName ){

  this.firstName = firstName;
  this.lastName = lastName;
  this.gender = "male";

};

// a new instance of Person can then easily be created as follows:
var clark = new Person( "Clark", "Kent" );

// Define a subclass constructor for for "Superhero":
var Superhero = function( firstName, lastName, powers ){

    // Invoke the superclass constructor on the new object
    // then use .call() to invoke the constructor as a method of
    // the object to be initialized.

    Person.call( this, firstName, lastName );

    // Finally, store their powers, a new array of traits not found in a normal "Person"
    this.powers = powers;
};

Superhero.prototype = Object.create( Person.prototype );
var superman = new Superhero( "Clark", "Kent", ["flight","heat-vision"] );
console.log( superman );

// Outputs Person attributes as well as powers

So when we execute

Person.call( this, firstName, lastName );

inside of Superhero subclass, the Superhero subclass will have access to Person's firstName, lastName and gender. Till that point everything looks legit to me, but when i see that stroke:

Superhero.prototype = Object.create( Person.prototype );

i'm wondering, why we are using Object.create, if we already have access to Person's methods? Also removing that stroke gives us exactly same result.

0

There are 0 answers