All, After reading this post, and did some test based on it .
function Shape() {
this.x = 0;
this.y = 0;
};
Shape.prototype.move = function(x, y) {
this.x += x;
this.y += y;
console.log("Shape moved.");
};
// Rectangle - subclass
function Rectangle() {
//Shape.call(this); //call super constructor.
};
Rectangle.prototype = Object.create(Shape.prototype);
var rect = new Rectangle();
alert(rect.x);
If I commented the code Shape.call(this);
in the Rectangle
, I found the rect.x
is underfined
instead of the value 0
.
And What make me confused is that I found in the best answer of the Post said:
"In javascript, every object has a secret link to the object which created it,forming a chain. When an object is asked for a property that it does not have,its parent object is asked... continually up the chain until the property is found or until the root object is reached."
So I can't understand why the rect
can't found x
in the prototype chain. The rect
is already inherited form Shape
. If the x
doesn't exist in the rect
, It supposed be found in his parent. right ?
And in my understanding .If using Shape.call(this);
, It just add a new x
property to the rect
, well ,that would not be a code reusing the original x
from parents. It just like the override property in the classical inheritance . that is add a new property into the sub class which have the same name and type as the one in the base class..I don't know if my understanding is right , if not . please correct me .Or was I missing something I didn't noticed ? thanks.
Edit
Below is my understanding based on the Thilo and Arun P Johny 's answers. please correct me if it is not right.
Before inheritance happen.
After inheritance executed.
So the x
only belong to the instance constructed by Shape
. thanks