vendredi 12 juin 2015

Javascript subclasses in Mixin Pattern missunderstanding [duplicate]

This question already has an answer here:

i'm new in javascript patterns and trying to understand them using Addy Osmani's explanations.

So currently i'm stuck in understanding of his subclasses explanations, here is code sample:

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

What bothers me, is that he uses

   Person.call( this, firstName, lastName );

with

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

Why is he using Object.create ? This code will work the same way without that stroke. Can someone please explain ?

Aucun commentaire:

Enregistrer un commentaire