Joe.wang
Joe.wang

Reputation: 11793

Object.create from an object

All, If I pass an object into the Object.create , that means creating a new object inherit from it. the code below proves it.

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

        Shape.prototype.move = function(x, y) {
            this.x += x;
            this.y += y;
            console.info("Shape moved.");
        };

        Rectangle = Object.create(Shape);
        Rectangle.__proto__==Shape;//it is true.yes, I can understand
        Rectangle//It is Function {} I can not understand it.
        Rectangle.constructor==Function//it is true.I can not understand it.

The diagram represent the relationship is below. But What I can not understand is the highlight part of it .What exactly is the Rectangle? I mean what is the Function{}, Where it come from? and also the Rectangle.constructor property, I don't know if all the object have the constructor property, and what does the constructor property use for? thanks.

PS: All the value above is caculated and watched in the FireBug.

enter image description here

Correct the diagram by the minitech's comments

enter image description here

Upvotes: 1

Views: 61

Answers (1)

Ry-
Ry-

Reputation: 224857

That's now how inheritance using Object.create works. It should look something like this:

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

Shape.prototype.move = function(x, y) {
    this.x += x;
    this.y += y;
    console.info("Shape moved.");
};

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

Rectangle.prototype = Object.create(Shape.prototype); // Leaving out the constructor business for simplicity

What you're doing there is duplicating the actual Shape function, so of course (being a function) its constructor is Function.

P.S. Rectangle.__proto__ = Shape isn't a comparison.

Upvotes: 2

Related Questions