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?

1

2 Answers 2

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'
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.