As a newcomer to ES6 classes, I am exploring how inheritance functions within it. To experiment with this concept, I have constructed a parent class named Modal
and a child class called ChildModal
. Below is the content of these classes:
class Modal {
constructor(selector, document) {
this.selector = selector;
this.document = document;
}
get title() {
return this._title;
}
set title(title) {
if(!title) {
throw new Error('Original title cannot be empty');
}
this._title = title;
}
defineNewTitle(newContent) {
this.title = newContent + this.title;
}
assignNewTitle() {
$(this.selector).text(this.title);
}
}
var modal = new Modal("#mainTitle");
modal.title = "Standards";
modal.defineNewTitle("JavaScript ");
modal.assignNewTitle();
class ChildModal extends Modal {
constructor(selector, title) {
super(selector, title);
}
defineChildTitle(title) {
this.title = title + this.title;
}
assignChildTitle() {
$(this.selector).text(this.title);
}
}
var child = new ChildModal("#childTitle");
child.defineChildTitle("Wow ");
child.assignChildTitle();
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<title>Class test</title>
<h1 id="mainTitle">
Main title
</h1>
<h2 id="childTitle">
Child title
</head>
<body>
<script src="Modal.js"></script>
</body>
</html>
In my implementation, I anticipate the h2 tag to display 'Wow JavaScript Standards', yet it currently shows 'Wow undefined'. The issue lies in the defineChildTitle
method where this.title
is not being recognized. Despite inheriting from the Modal
class in the constructor function of ChildModal
, why does this.title
not reflect as 'JavaScript Standard' as expected?