【发布时间】:2017-01-02 17:29:24
【问题描述】:
这几天我一直在学习 ECMAScript 6 类、Mixins 和其他特性,但我不确定我对用例的理解是否正确。下面是一个带有类、子类和 Mixins 的示例的 sn-p。
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}`);
上面的代码没有错误,我得到了正确的输出。但是,我的 Mixins 实现在语义上是否正确?在给定的上下文中使用 Jobs 和 Greetings Mixin 有意义吗?我读了一篇博客Mixins and Javascript: The Good, the Bad, and the Ugly.,其中他们将mixin 定义为抽象子类。查看示例,他们为给定的类添加了一些小功能。由于这听起来与装饰器的定义相似,因此我查看了Python: Use of decorators v/s mixins? 的公认答案的差异。它说:
Mixins 添加了新功能。装饰器用于修改现有的 功能。
这让我想到如果Jobs 和Greetings 是Mixins,那么在这种情况下你会给装饰器举什么例子?如果我有任何错误,请提供正确答案的代码块。
另外,有没有更好的方法来提供输入参数,而不是在实例化 WorkingPerson 时抛出一些原始对象作为参数?
【问题讨论】:
-
我真的不明白
Greetings和Jobs的意义所在。他们只是定义空方法。只需使用class WorkingPerson extends Person -
我也是这么想的。但如果你要为 Person 类创建 Mixins,它们会是什么?
-
我不喜欢 mixins。如果我真的需要多重继承,I would probably use a proxy.
-
@AjayH 该问题不包含需要 mixins 的示例。事实上,类 mixin 在 JS 中并没有那么流行,并且经常表明类设计存在问题。