Core JavaScript

Overriding Methods

This JavaScript example demonstrates how to override a method in JavaScript. The class CDog is a based class that implements a Speak() method that prints Bark. The classes CBigDog and CSmallDog extend the class CDog and override the method Speak() and print out Woof and Arf, respectively.

Overriding.html

<!DOCTYPE html>
<html>
<head>
    <title>XoaX.net's Javascript</title>
</head>
<body>
    <script type="text/javascript" src="Overriding.js"></script>
</body>
</html>

Overriding.js

class CDog {
	constructor() {
	}
	Speak() {
		document.write("Bark" + "<br />");
	}
}

class CBigDog extends CDog {
	constructor() { super();}
	Speak() {
		document.write("Woof" + "<br />");
	}
}

class CSmallDog extends CDog {
	constructor() { super();}
	Speak() {
		document.write("Arf" + "<br />");
	}
}

var qDog = new CDog();
var qBigDog = new CBigDog();
var qSmallDog = new CSmallDog();

qDog.Speak();
qBigDog.Speak();
qSmallDog.Speak();
 

Output

 
 

© 2007–2025 XoaX.net LLC. All rights reserved.