Your browser does not support JavaScript!
Upvotes Anonymous 0 User 0

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>
Was this helpful?

Comments

Leave a Comment

I agree to the Terms of Service
Design © 2015, Downranked, LLC.,
Original user code contributions under MIT License