How to use mixins to extend the functionality of classes?
Last Updated :
13 Dec, 2023
In general, a class can extend only one class at a time to extend its behavior by inheriting the member functions and variables of the class. But in TypeScript, we are allowed to use the mixins that are used to extend the functionality of a class without extending them. It helps us to write reusable code that can be used to extend the functionality of other classes as well.
We can use the mixins to extend the functionality of the classes by assigning them to the class using the assign() method. The assign() method is a method of Object constructor that takes the class with its prototype and the name of the mixin as parameters to extend the functionality of the specified class.
Syntax:
Object.assign(class.prototype, mixinName);
Example: The below example will illustrate the use of the assign method to extend the functionality of the class by adding a method using mixin.
Javascript
let testingMixin = {
greet(){
console.log(
`This method is defined inside the
testing mixin and invoked
using testing class object.`
)
}
}
class testingClass{
name: string;
constructor(name: string){
this .name = name;
}
logMessage(){
console.log(`Hey ${ this .name},
Welcome to GeeksforGeeks!`);
}
}
Object.assign(testingClass.prototype,
testingMixin);
const testingObj = new
testingClass( "Emrit" );
testingObj.logMessage();
testingObj.greet();
|
Output:
Hey Emrit, Welcome to GeeksforGeeks!
This method is defined inside the testing mixin and invoked using class object.
Example 2: The below example will assign the mixin with two methods and uses the member variables of class inside them.
Javascript
let testingMixin = {
greet() {
console.log(`Hey ${ this .name},
Welcome to GeeksforGeeks!`)
}
getDetails() {
console.log(`You are working as a
${ this .designation} at ${ this .company}.`)
}
}
class testingClass {
name: string;
designation: string;
company: string;
constructor(name: string,
designation: string,
company: string) {
this .name = name;
this .designation = designation;
this .company = company;
}
logMessage() {
console.log(
`This method is defined inside
the testing class as
member function .`
);
}
}
Object.assign(testingClass.prototype,
testingMixin);
const testingObj = new testingClass( "Emrit" ,
"Software Developer" , "Google" );
testingObj.logMessage();
testingObj.greet();
testingObj.getDetails();
|
Output:
This method is defined inside the testing class as member function.
Hey Emrit, Welcome to GeeksforGeeks!
You are working as a Software Developer at Google.
Share your thoughts in the comments
Please Login to comment...