Inheritance in JavaScript
📌 Notes on the Code
1. Understanding the User
Class
class User {
constructor(username) {
this.username = username;
}
logMe() {
console.log(`USERNAME is ${this.username}`);
}
}
How It Works
constructor(username)
: Initializes theusername
property.logMe()
: Logs theusername
to the console.
2. Understanding the Teacher
Subclass
class Teacher extends User {
constructor(username, email, password) {
super(username); // Calls the User class constructor
this.email = email;
this.password = password;
}
addCourse() {
console.log(`A new course was added by ${this.username}`);
}
}
How It Works
extends User
:Teacher
inherits fromUser
, meaning it has access toUser
's methods.super(username)
: CallsUser
's constructor to ensureusername
is set before addingemail
andpassword
.- New Method (
addCourse()
): A method specific toTeacher
, not available inUser
.
3. Creating Instances
const chai = new Teacher('chai', 'chai@teacher.com', '123');
chai.logMe(); // ✅ Inherited from User
- Object
chai
belongs toTeacher
but can uselogMe()
fromUser
.
const masalaChai = new User('masalaChai');
masalaChai.logMe(); // ✅ "USERNAME is masalaChai"
- Object
masalaChai
is an instance ofUser
, so it can only uselogMe()
.
4. Using instanceof
console.log(chai instanceof User); // ✅ true
- Why is
chai instanceof User
true?chai
is an instance ofTeacher
, which inherits fromUser
.- JavaScript checks the prototype chain, and since
Teacher
extendsUser
,chai
is also considered an instance ofUser
.
📌 Summary of Key Concepts
Feature | Explanation |
---|---|
Inheritance (extends User ) | Teacher gets all User methods. |
Calling Parent Constructor (super(username) ) | Ensures username is set before adding new properties. |
Method Overriding | Teacher can override logMe() if needed. |
Prototype Chain | chai is an instance of both Teacher and User . |
Instanceof Check (instanceof ) | Checks if an object is derived from a class. |
📌 Trivia
-
What happens if
super(username)
is not called inTeacher
?- JavaScript will throw an error:
Must call super constructor in derived class before accessing 'this' or returning from derived constructor
- This happens because
Teacher
is a subclass, and it must initialize the parent class before usingthis
.
- JavaScript will throw an error:
-
Can
instanceof
check multiple levels of inheritance?- Yes!
console.log(chai instanceof Teacher); // ✅ true
console.log(chai instanceof User); // ✅ true (because Teacher extends User)
- Yes!
📌 How Inheritance Works in the Background
1. The Prototype Chain & Inheritance
In JavaScript, inheritance is implemented using prototypes. When an object accesses a property or method:
- JavaScript first looks for the property/method in the object itself.
- If not found, it searches in the object's prototype (
__proto__
), which refers to the class it was created from. - If still not found, it continues up the prototype chain until it reaches
Object.prototype
, the base prototype of all objects.
2. Step-by-Step Execution of the Code
(1) Creating a Teacher
Instance
const chai = new Teacher('chai', 'chai@teacher.com', '123');
- JavaScript follows these steps in the background:
- Calls the
Teacher
constructor. super(username)
is executed, invoking theUser
constructor.User
constructor assignsthis.username = username
.- Control returns to
Teacher
, wherethis.email
andthis.password
are assigned.
- Calls the
(2) The Prototype Chain
When we create chai
as a Teacher
object, it gets the following prototype chain:
chai ---> Teacher.prototype ---> User.prototype ---> Object.prototype ---> null
chai
(instance ofTeacher
) has:username
,email
, andpassword
properties.- Access to
addCourse()
fromTeacher.prototype
. - Access to
logMe()
fromUser.prototype
(inherited).
3. How Methods Are Accessed in the Prototype Chain
(1) Calling chai.logMe();
chai.logMe();
- JavaScript first looks for
logMe()
inchai
itself. ❌ Not found. - Then, it checks
Teacher.prototype
. ❌ Not found. - Then, it checks
User.prototype
. ✅ Found → ExecuteslogMe()
.
(2) Calling chai.addCourse();
chai.addCourse();
- JavaScript first looks for
addCourse()
inchai
itself. ❌ Not found. - Then, it checks
Teacher.prototype
. ✅ Found → ExecutesaddCourse()
.
4. How instanceof
Works Internally
console.log(chai instanceof Teacher); // ✅ true
console.log(chai instanceof User); // ✅ true
console.log(chai instanceof Object); // ✅ true
instanceof
works by checking the prototype chain:chai.__proto__ === Teacher.prototype
✅true
Teacher.prototype.__proto__ === User.prototype
✅true
User.prototype.__proto__ === Object.prototype
✅true
Object.prototype.__proto__ === null
✅ Ends here.
Since User
is in the chain, chai instanceof User
returns true
.
📌 Summary of How Inheritance Works in Background
Step | What Happens? |
---|---|
1. Class Definition | Teacher extends User , meaning Teacher.prototype is linked to User.prototype . |
2. Instance Creation | const chai = new Teacher('chai', 'chai@teacher.com', '123'); |
3. Calling logMe() | JavaScript searches in chai → Teacher.prototype → User.prototype , finds logMe() , and executes it. |
4. Calling addCourse() | JavaScript finds addCourse() in Teacher.prototype and executes it. |
5. instanceof Checks | Checks the prototype chain to determine if chai is an instance of Teacher , User , or Object . |
📌 Trivia
-
Can
Teacher
overridelogMe()
?- Yes! If
Teacher.prototype
defineslogMe()
, it will be called instead of the one fromUser.prototype
.
- Yes! If
-
What happens if
super(username)
is not called?- JavaScript will throw an error because
this
cannot be used before callingsuper()
in a derived class.
- JavaScript will throw an error because