本文介绍了ES6:我使用Classes& mixin在JavaScript中正确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

过去几天我一直在学习ECMAScript 6 Classes,Mixins和其他功能,但我不知道我对用例的理解是否正确。以下是类,子类和Mixins的示例代码片段。

  class Person {
constructor(opts){
for(let prop of Object.keys )){
this [prop] = opts [prop];
}
Person.count ++;
}

static count = 0;
}

//问候Mixin
const Greetings = Person => class extends Person {
sayHello(){}
}

// Job Mixin
const Jobs = Person => class extends Person {
getJobs(){}
getSalary(){}
setJobs(){}
setSalary(){}
}

//子类
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(`啊!离开这里!
}

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 WorkPerson({name:'Morris',jobs:['Televangelist'],salary:30000});
console.log(`人数= $ {Person.count}`);

上面的代码没有错误,我得到正确的输出。但是,我的Mixin语法正确吗?在给定的上下文中有一个 Jobs Greetings Mixin是否有意义?我阅读了一个博客。它说:

这让我想到如果 code>和问候语是Mixins,那么在这个上下文中你将为装饰器提供什么样的例子?如果我以任何方式出错,请提供正确答案的代码块。



另外,在实例化一个 WorkingPerson

解决方案

不,mixins未正确应用。



Person => class extends Person {...} 是基本的继承,可以相应地实现:

  class GreetingPerson扩展人{
sayHello(){...}
}

如果有多个不相关的类应该具有相同的方法集合,请考虑应用构成继承

  function mixin(obj){
return function(target){
Object.assign(target.prototype,obj) ;
返回目标;
}
}

class GreetingBeing {
sayHello(){...}
}

const Person = mixin (GreetingBeing.prototype)(类Person extends Biped {...})

//或对于ES.Next,
// @mixin(GreetingBeing.prototype)
/ / class Person extends Biped {...}

或实例:

  class Person extends Biped {
constructor()
super();
Object.assign(this,GreetingBeing.prototype);
}
}

请注意, mixin helper / decorator不做多重继承。它所做的只是将自己的枚举属性从 GreetingBeing.prototype 复制到 Person.prototype


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:

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?

解决方案

No, mixins are not applied correctly.

Person => class extends Person{...} is basic inheritance and it can be achieved accordingly:

class GreetingPerson extends Person {
    sayHello() {...}
}

If there are multiple unrelated classes that are supposed to have the same set of methods, consider applying composition over inheritance principle.

For the rest of the cases (e.g. polymorphism that cannot be refactored in accordance with mentioned principle) mixins can be applied to either prototype:

function mixin(obj) {
  return function (target) {
    Object.assign(target.prototype, obj);
    return target;
  }
}

class GreetingBeing {
  sayHello() {...}
}

const Person = mixin(GreetingBeing.prototype)(class Person extends Biped { ... })

// or for ES.Next,
// @mixin(GreetingBeing.prototype)
// class Person extends Biped { ...}

or instance:

class Person extends Biped {
  constructor()
    super();
    Object.assign(this, GreetingBeing.prototype);
  }
}

Notice that mixin helper/decorator doesn't do multiple inheritance. All it does is copying own enumerable properties from GreetingBeing.prototype to Person.prototype)

这篇关于ES6:我使用Classes& mixin在JavaScript中正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 00:15