Simple JavaScript Inheritance

Using the prototype object in JavaScript, we can create objects that inherit properties from other objects. (Similar to class-based inheritance in Java, Python, etc.)

Here's an example:

<!DOCTYPE html>
<html>
<head>
    <title>JS Inheritance</title>
</head>
<body>
<script>

    function Shape() {
    }

    Shape.prototype.Init = function (numSides) {
        this.numSides = numSides;
    }

    Shape.prototype.Draw = function () {
        alert('This ' + this.name + ' has ' + this.numSides + ' sides');
    };


    function Rectangle() {
    }

    Rectangle.prototype = new Shape;
    Rectangle.prototype.superclass = Shape.prototype;

    Rectangle.prototype.Init = function () {
        this.name = 'rectangle';
        this.superclass.Init.call(this, 4);
    };

    var rect = new Rectangle();
    rect.Init();
    rect.Draw();

</script>
</body>
</html>

Comments

Leave a comment

What color are green eyes? (spam prevention)
Submit
Code under MIT License unless otherwise indicated.
© 2020, Downranked, LLC.