It is essential to comprehend the concept of late binding. It will help us sum up the relationships between classes bound by inheritance.
In the previous lesson, we introduced the base class HTMLElement, which we utilize to refer to properties within it. The class this
serves as a template for all tags and recognizes how to function with attributes.
// Base class for all tags
// It knows how to work with attributes.
class HTMLElement {
constructor(attributes = {}) {
this.attributes = attributes;
}
getAttribute(key) {
return this.attributes[key];
}
}
Suppose we create an HTMLAnchorElement class object (which inherits HTMLElement). Then what class object would be this
inside the methods of the parent class? The correct answer is HTMLAnchorElement, which is the class whose object we're creating right now. Take a look at this example:
Suppose we generate a new class object, HTMLAnchorElement, which inherits from HTMLElement. Consequently, what class object would we identify as this within the parent class methods?
The correct answer is HTMLAnchorElement since it is the class object currently being created. Observe the following example:
class A {
constructor() {
this.name = 'From A';
}
getName() {
console.log(this.constructor);
return this.name;
}
}
class B extends A {}
const b = new B();
console.log(b.getName());
// [class B extends A]
// => From A
So, this
feature is known as late binding. It suggests that the type of this is unknown at the time the class is defined. The current object may be an object of any class that inherits from the current class.
It turns out that the code inside the base class has been replicated and moved to each descendant class. Regardless of how deep the inheritance hierarchy is, this will always refer to a class object constructed in the code.
Late binding is a crucial component in the operation of inheritance. Without it, interactions between classes would become much more convoluted and restricted.
Each object would have to distinguish which class the properties and methods in the inheritance chain belong to. As a result, we need a special syntax to gain access to them.
Recommended materials
Are there any more questions? Ask them in the Discussion section.
The Hexlet support team or other students will answer you.
For full access to the course you need a professional subscription.
A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.