What techniques can be used to define a class in JavaScript, and what are their trade-offs?

后端 未结 19 1701
庸人自扰
庸人自扰 2020-11-22 07:26

I prefer to use OOP in large scale projects like the one I\'m working on right now. I need to create several classes in JavaScript but, if I\'m not mistaken, there are at le

19条回答
  •  不要未来只要你来
    2020-11-22 08:05

    ES2015 Classes

    In the ES2015 specification, you can use the class syntax which is just sugar over the prototype system.

    class Person {
      constructor(name) {
        this.name = name;
      }
      toString() {
        return `My name is ${ this.name }.`;
      }
    }
    
    class Employee extends Person {
      constructor(name, hours) {
        super(name);
        this.hours = hours;
      }
      toString() {
        return `${ super.toString() } I work ${ this.hours } hours.`;
      }
    }
    

    Benefits

    The main benefit is that static analysis tools find it easier to target this syntax. It is also easier for others coming from class-based languages to use the language as a polyglot.

    Caveats

    Be wary of its current limitations. To achieve private properties, one must resort to using Symbols or WeakMaps. In future releases, classes will most likely be expanded to include these missing features.

    Support

    Browser support isn't very good at the moment (supported by nearly everyone except IE), but you can use these features now with a transpiler like Babel.

    Resources

    • Classes in ECMAScript 6 (final semantics)
    • What? Wait. Really? Oh no! (a post about ES6 classes and privacy)
    • Compatibility Table – Classes
    • Babel – Classes

提交回复
热议问题