gpt4 book ai didi

javascript - ES6 : Am I using Classes & Mixins Correctly in JavaScript?

转载 作者:行者123 更新时间:2023-11-29 10:07:00 25 4
gpt4 key购买 nike

<分区>

过去几天我一直在学习 ECMAScript 6 类、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}`);

上面的代码没有错误,我得到了正确的输出。但是,我的 Mixins 实现在语义上是否正确?对于给定的上下文,使用 JobsGreetings Mixin 是否有意义?我看了一篇博客Mixins and Javascript: The Good, the Bad, and the Ugly.他们在其中将 mixins 定义为抽象子类。查看示例,他们向给定类添加了小功能。由于这听起来与 Decorator 的定义相似,所以我查找了接受的答案 Python: Use of decorators v/s mixins? 的区别。 .它说:

Mixins add new functionalities. Decorators are used to modify existing functionalities.

这让我想到,如果 JobsGreetings 是 Mixins,那么在这种情况下您会为装饰器举出什么例子?如果我有任何错误,请提供正确答案的代码块。

此外,在实例化 WorkingPerson 时,是否有更好的方法来提供输入参数而不是将一些原始对象作为参数抛出?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com