0

I'd like a subclass' constructor to call it's parent's constructor before executing itself, with the Object.create pattern.

Using new Parent()

var Parent = function(){ console.log( 'Parent' ) };
var Child  = function(){ console.log( 'Child' ) };
Child.prototype = new Parent(); // Prints 'Parent'
var child = new Child(); // Prints 'Child'

Using Object.create

var Parent = function(){ console.log( 'Parent' ) };
var Child  = function(){ console.log( 'Child' ) };
Child.prototype = Object.create( Parent.prototype );
var child = new Child(); // I'd like this to print 'Parent' then 'Child'

Is this even possible? Can I add something like Parent.call( this ) in the Child constructor?

ldiqual
  • 15,015
  • 6
  • 52
  • 90
  • possible duplicate of [Correct javascript inheritance](http://stackoverflow.com/questions/10898786/correct-javascript-inheritance) – Bergi Feb 18 '14 at 19:32

2 Answers2

1

Can I add something like Parent.call( this ) in the Child constructor?

Yes, just do exactly this.

var Parent = function(){ console.log( 'Parent' ) };
var Child  = function(){ Parent.call(this); console.log( 'Child' ) };
Child.prototype = Object.create( Parent.prototype ); // should print nothing
var child = new Child(); // prints 'Parent' then 'Child'
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

Great question. You already answered it, though.

var Parent = function(){console.log('Parent')};
var Child = function(){
  console.log('Child')
  Parent.call(this);
};
Child.prototype = new Parent();
var child = new Child();

in the Firebug console produces

Parent
Child
Parent
Object { }

as output.