I have been learning about ECMAScript 6 Classes, Mixins and other features for the past few days, but I'm not sure if my understanding of use cases is correct. Below is a snippet of an example with Classes, Subclasses and Mixins.
class Person{
constructor (opts){
for(let prop of Object.keys(opts)){
this[prop] = opts[prop];
}
Person.count++;
}
static count = 0;
}
//Greeting Mixin
const Greetings = Person => class extends Person{
sayHello(){}
}
//Job Mixin
const Jobs = Person => class extends Person{
getJobs(){}
getSalary(){}
setJobs(){}
setSalary(){}
}
//Subclass
class WorkingPerson extends Jobs(Greetings(Person)){
constructor(opts){
super(opts);
//this.type = 'nice';
}
sayHello(){
if(this.type == 'nice')
console.log(`Hello there! Wonderful day isnt it?`);
else
console.log(`Ah! Get out of here!`);
}
getJobs(){
return this.jobs;
}
setJobs(...jobs){
this.jobs.push(jobs);
}
getSalary(){
return this.salary;
}
setSalary(salary){
this.salary = salary;
}
}
let wp = new WorkingPerson({name:'Ajay',jobs:['Digital Evangelist'],salary:10000});
let wp2 = new WorkingPerson({name:'Ron',jobs:['Entertainer'],salary:20000});
let wp3 = new WorkingPerson({name:'Morris',jobs:['Televangelist'],salary:30000});
console.log(`Number of people = ${Person.count}`);
There are no errors in the code above and I get the correct output. However, are my implementations of Mixins semantically correct? Does it make sense to have a Jobs
and Greetings
Mixin for the given context? I read a blog Mixins and Javascript: The Good, the Bad, and the Ugly. in which they define mixins as abstract subclasses. Looking at the examples, they added small functionality to a given class. Since this sounded similar to the definition of a Decorator, I looked the difference up to the accepted answer of Python: Use of decorators v/s mixins? .It says:
Mixins add new functionalities. Decorators are used to modify existing functionalities.
This got me thinking if the Jobs
and Greetings
are Mixins, then what example would you give for a decorator in this context? If I am wrong in any way, please provide code blocks of the correct answer.
Also, is there a better way to supply input arguements instead of throwing some raw object as a parameter while instantiating a WorkingPerson
?