User Tools

Site Tools


java-script:multiple-inheritance

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
java-script:multiple-inheritance [2023/07/26 19:27] odeftajava-script:multiple-inheritance [2023/07/26 19:39] (current) odefta
Line 11: Line 11:
  
 ===== Java Script Mixins ===== ===== Java Script Mixins =====
 +
 +==== Mixins using class syntax ====
  
 ::A **mixin** is a class whose methods are intended to be added to (or "mixed in" to) other classes.:: \\   ::A **mixin** is a class whose methods are intended to be added to (or "mixed in" to) other classes.:: \\  
Line 31: Line 33:
 const AnimalMixin = Base => class extends Base { const AnimalMixin = Base => class extends Base {
     eats() {     eats() {
-        return `${this.name} eats.`;+        return `${this.name} eats like an animal.`;
     }     }
 }; };
Line 55: Line 57:
 While mixins can be useful for sharing behavior between classes, they should be used sparingly as they can make code more complex and harder to follow. While mixins can be useful for sharing behavior between classes, they should be used sparingly as they can make code more complex and harder to follow.
 </note> </note>
 +
 +==== Mixins using Object.assign ====
 +
 +Same functionality can be achieved using **Object.assign** approach. \\
 +;;;In this case, we're directly adding the methods from AnimalMixin to the prototype of Employee class using Object.assign(). This way, all instances of Employee will have access to the eats method.;;;
 +
 +<code javascript Person.js>
 +let AnimalMixin = {
 +    eats() {
 +        return `${this.name} eats.`;
 +    }
 +};
 +
 +class Employee {
 +    constructor(name, age, salary, jobTitle) {
 +        this.name = name;
 +        this.age = age;
 +        this.salary = salary;
 +        this.jobTitle = jobTitle;
 +    }
 +
 +    description() {
 +        return `A person named ${this.name} who is ${this.age} years old`;
 +    }
 +}
 +
 +Object.assign(Employee.prototype, AnimalMixin);
 +
 +let employee = new Employee("Aurel", 30, 15000, "CEO boss");
 +console.log(employee.eats()); // Aurel eats.
 +</code>
 +
 +<note>
 +Using class syntax can be more straightforward if you're already working with classes and want to take advantage of built-in class features like super calls and static properties/methods.
 +</note>
 +
 +<note>
 +On the other hand, Object.assign() can be more flexible and dynamic, since it allows you to copy methods onto any object, not just class prototypes.
 +</note>
 +
 +
 +
 +
  
  
java-script/multiple-inheritance.1690388862.txt.gz · Last modified: 2023/07/26 19:27 by odefta