-1

All , In the classical inheritance language. such as Java , c# etc, It is true a new instance initialization of a sub Class will cause the base Class constructor execution before the sub Class's constructor is executed. But I am not sure whether It will be same in the javascript inheritance. Let's take a example . Says your have the code like below .

function Shape() {
    this.x = 0;
    this.y = 0;
};

If there is an object name rect inherit from Shape . supposed the constructor of Rectangle looks like this.

function Rectangle(){

};
Rectangle.prototype = Object.create(Shape.prototype);
var rect= new Rectangle();

Would the constructor Shape will be executed when the constructor Rectangle is executed ? thanks.

Joe.wang
  • 11,537
  • 25
  • 103
  • 180

1 Answers1

1

This is how you normally do inheritance in JavaScript:

function Shape() {
    this.x = 0;
    this.y = 0;
}

function Rectangle() {
    Shape.call(this);
}

Rectangle.prototype = Object.create(Shape.prototype);

Notice that you're calling Shape.call(this) from inside the Rectangle constructor. This is like calling the base/super class constructor in other languages. Without doing so your Rectangle objects would not have the x and y properties defined inside the Shape constructor.

For more details read the following answer: https://stackoverflow.com/a/15497685/783743

Community
  • 1
  • 1
Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299
  • Thanks your kindly answer , It is nice to meet you again. :) actually I found what I really want to ask is another question. Could you please review [here](http://stackoverflow.com/questions/16129365/in-prototype-inheritance-program-when-a-property-not-found-in-a-specified-object) – Joe.wang Apr 21 '13 at 08:40