Search code examples
javascriptjavascript-objectsdom-events

Something about prototype in Javascript


I write the Javascript code as follow:

function Shape() {
  this.x = 0;
  this.y = 0;
}
function Rectangle() {
   Shape.call(this); // call super constructor.
}
Rectangle.prototype = Object.create(Shape.prototype);
function Tmp() {
   this.a = 0;
   this.b = 0;
}
Rectangle.prototype.constructor = Tmp;
var rect = Object.create(Rectangle.prototype);
console.log(rect)

then the output is:

enter image description here

The rect should be initialized by constructor function Tmp.my question is where is the attribution a and b of the object rect which initialized by the constructor function Tmp?


Solution

  • The rect should be initialized by constructor function Tmp

    If you want that, you'd do:

    Tmp.call(rect);
    

    ...after

    var rect = Object.create(Rectangle.prototype);
    

    function Shape() {
        this.x = 0;
        this.y = 0;
    }
    function Rectangle() {
         Shape.call(this); // call super constructor.
    }
    Rectangle.prototype = Object.create(Shape.prototype);
    function Tmp() {
       this.a = 0;
       this.b = 0;
    }
    //Rectangle.prototype.constructor = Tmp;
    var rect = Object.create(Rectangle.prototype);
    Tmp.call(rect);
    console.log(rect);

    Object.create doesn't call any functions at all, it just creates the object with the given prototype. So neither Rectangle nor Shape nor Tmp is called by doing var rect = Object.create(Rectangle.prototype);.

    Or if you also want Rectangle to do its job, replace the Object.create call with:

    var rect = new Rectangle();
    Tmp.call(rect);
    

    It's very strange to set the constructor property of Rectangle.prototype to Tmp, not Rectangle. I would strongly suggest not doing that. And there's no need to if all you want is for Tmp to initialize an instance. The constructor property of the object referenced by SomeFunction.prototype should be SomeFunction, never anything else.