Good Example of JavaScript's Prototype-Based Inheritance

后端 未结 11 780
情书的邮戳
情书的邮戳 2020-11-29 15:52

I have been programming with OOP languages for over 10 years but I\'m learning JavaScript now and it\'s the first time I\'ve encountered prototype-based inheritance. I tend

11条回答
  •  迷失自我
    2020-11-29 16:32

    function Shape(x, y) {
        this.x = x;
        this.y = y;
    }
    
    // 1. Explicitly call base (Shape) constructor from subclass (Circle) constructor passing this as the explicit receiver
    function Circle(x, y, r) {
        Shape.call(this, x, y);
        this.r = r;
    }
    
    // 2. Use Object.create to construct the subclass prototype object to avoid calling the base constructor
    Circle.prototype = Object.create(Shape.prototype);
    

提交回复
热议问题