JavaScript - Object Inheritance

[ECMAScript 5]


Object Masquerading / Constructor Stealing ( call() & apply() )

  • Call SuperType constructor from within the SubType constructor 
  • Arguments can be passed from SubType to SuperType
  • Methods must be defined inside constructor - duplication
  • Methods on SuperTypes prototype are not available in SubType.

    function Subtype(){
        SuperType.call( this )
    }

Prototype Chaining

   SubType.prototype = new SuperType();

  • Reference values (in SuperType) are shared with all instances of SuperType.
  • Arguments cant be passed into SuperType constructor.

Hybrid Method / Combination Inheritance

Use object masquerading to inherit properties from the constructor and prototype chaining to inherit methods from the prototype object.
  • Call SuperType constructor from SubTypeConstructor (adds all SuperType properties to SubType)
  • Replace SubType.prototype with instance of SuperType ( adds SuperType.prototype properties to SubType )
  • Preserves instanceof() and isprototypeof() behaviour.
  • SuperType constructor is called twice
    • Once in the explicit call within the SubType Constructor
    • Second when the SubType prototype is assigned.


Prototypical Inheritance

  • Creates object based on existing Object without using Types.
  • ECMAScript has Object.create( o1, o2 ) with the same behaviour.

    function create( obj ) {
        function F(){};
        F.prototype = o;
        return new F();
    }


Parasitic Combination Inheritance

SuperType( name ){
    this.name = name ;
}

SuperType.prototype.getName(){
    return name;
}

SubType( name, value ){
    SuperType.call( this, name ); // Constructor Stealing
    this.value = value;
}

inheritPrototype ( Subtype, SuperType );

function inheritPrototype( subType, superType ){

    var newProto = create(SuperType.prototype); // create object
    newProto.constructor = SubType;
    SubType.prototype = newProto;
}


Subclassing



prototype can be accessed by

  1. instance.prototype
  2. instance.constructor.prototype

No comments:

Post a Comment