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>
Leave a comment