ES6 class variable alternatives

前端 未结 15 2126
长发绾君心
长发绾君心 2020-11-22 06:04

Currently in ES5 many of us are using the following pattern in frameworks to create classes and class variables, which is comfy:



        
相关标签:
15条回答
  • 2020-11-22 06:10

    2018 update:

    There is now a stage 3 proposal - I am looking forward to make this answer obsolete in a few months.

    In the meantime anyone using TypeScript or babel can use the syntax:

    varName = value
    

    Inside a class declaration/expression body and it will define a variable. Hopefully in a few months/weeks I'll be able to post an update.

    Update: Chrome 74 now ships with this syntax working.


    The notes in the ES wiki for the proposal in ES6 (maximally minimal classes) note:

    There is (intentionally) no direct declarative way to define either prototype data properties (other than methods) class properties, or instance property

    Class properties and prototype data properties need be created outside the declaration.

    Properties specified in a class definition are assigned the same attributes as if they appeared in an object literal.

    This means that what you're asking for was considered, and explicitly decided against.

    but... why?

    Good question. The good people of TC39 want class declarations to declare and define the capabilities of a class. Not its members. An ES6 class declaration defines its contract for its user.

    Remember, a class definition defines prototype methods - defining variables on the prototype is generally not something you do. You can, of course use:

    constructor(){
        this.foo = bar
    }
    

    In the constructor like you suggested. Also see the summary of the consensus.

    ES7 and beyond

    A new proposal for ES7 is being worked on that allows more concise instance variables through class declarations and expressions - https://esdiscuss.org/topic/es7-property-initializers

    0 讨论(0)
  • 2020-11-22 06:10

    Just to add to Benjamin's answer — class variables are possible, but you wouldn't use prototype to set them.

    For a true class variable you'd want to do something like the following:

    class MyClass {}
    MyClass.foo = 'bar';
    

    From within a class method that variable can be accessed as this.constructor.foo (or MyClass.foo).

    These class properties would not usually be accessible from to the class instance. i.e. MyClass.foo gives 'bar' but new MyClass().foo is undefined

    If you want to also have access to your class variable from an instance, you'll have to additionally define a getter:

    class MyClass {
        get foo() {
            return this.constructor.foo;
        }
    }
    
    MyClass.foo = 'bar';
    

    I've only tested this with Traceur, but I believe it will work the same in a standard implementation.

    JavaScript doesn't really have classes. Even with ES6 we're looking at an object- or prototype-based language rather than a class-based language. In any function X () {}, X.prototype.constructor points back to X. When the new operator is used on X, a new object is created inheriting X.prototype. Any undefined properties in that new object (including constructor) are looked up from there. We can think of this as generating object and class properties.

    0 讨论(0)
  • 2020-11-22 06:12

    Babel supports class variables in ESNext, check this example:

    class Foo {
      bar = 2
      static iha = 'string'
    }
    
    const foo = new Foo();
    console.log(foo.bar, foo.iha, Foo.bar, Foo.iha);
    // 2, undefined, undefined, 'string'
    
    0 讨论(0)
  • 2020-11-22 06:13

    What about the oldschool way?

    class MyClass {
         constructor(count){ 
              this.countVar = 1 + count;
         }
    }
    MyClass.prototype.foo = "foo";
    MyClass.prototype.countVar = 0;
    
    // ... 
    
    var o1 = new MyClass(2); o2 = new MyClass(3);
    o1.foo = "newFoo";
    
    console.log( o1.foo,o2.foo);
    console.log( o1.countVar,o2.countVar);
    

    In constructor you mention only those vars which have to be computed. I like prototype inheritance for this feature -- it can help to save a lot of memory(in case if there are a lot of never-assigned vars).

    0 讨论(0)
  • 2020-11-22 06:15

    In your example:

    class MyClass {
        const MY_CONST = 'string';
        constructor(){
            this.MY_CONST;
        }
    }
    

    Because of MY_CONST is primitive https://developer.mozilla.org/en-US/docs/Glossary/Primitive we can just do:

    class MyClass {
        static get MY_CONST() {
            return 'string';
        }
        get MY_CONST() {
            return this.constructor.MY_CONST;
        }
        constructor() {
            alert(this.MY_CONST === this.constructor.MY_CONST);
        }
    }
    alert(MyClass.MY_CONST);
    new MyClass
    
    // alert: string ; true
    

    But if MY_CONST is reference type like static get MY_CONST() {return ['string'];} alert output is string, false. In such case delete operator can do the trick:

    class MyClass {
        static get MY_CONST() {
            delete MyClass.MY_CONST;
            return MyClass.MY_CONST = 'string';
        }
        get MY_CONST() {
            return this.constructor.MY_CONST;
        }
        constructor() {
            alert(this.MY_CONST === this.constructor.MY_CONST);
        }
    }
    alert(MyClass.MY_CONST);
    new MyClass
    
    // alert: string ; true
    

    And finally for class variable not const:

    class MyClass {
        static get MY_CONST() {
            delete MyClass.MY_CONST;
            return MyClass.MY_CONST = 'string';
        }
        static set U_YIN_YANG(value) {
          delete MyClass.MY_CONST;
          MyClass.MY_CONST = value;
        }
        get MY_CONST() {
            return this.constructor.MY_CONST;
        }
        set MY_CONST(value) {
            this.constructor.MY_CONST = value;
        }
        constructor() {
            alert(this.MY_CONST === this.constructor.MY_CONST);
        }
    }
    alert(MyClass.MY_CONST);
    new MyClass
    // alert: string, true
    MyClass.MY_CONST = ['string, 42']
    alert(MyClass.MY_CONST);
    new MyClass
    // alert: string, 42 ; true
    
    0 讨论(0)
  • 2020-11-22 06:15

    The way I solved this, which is another option (if you have jQuery available), was to Define the fields in an old-school object and then extend the class with that object. I also didn't want to pepper the constructor with assignments, this appeared to be a neat solution.

    function MyClassFields(){
        this.createdAt = new Date();
    }
    
    MyClassFields.prototype = {
        id : '',
        type : '',
        title : '',
        createdAt : null,
    };
    
    class MyClass {
        constructor() {
            $.extend(this,new MyClassFields());
        }
    };
    

    -- Update Following Bergi's comment.

    No JQuery Version:

    class SavedSearch  {
        constructor() {
            Object.assign(this,{
                id : '',
                type : '',
                title : '',
                createdAt: new Date(),
            });
    
        }
    }
    

    You still do end up with 'fat' constructor, but at least its all in one class and assigned in one hit.

    EDIT #2: I've now gone full circle and am now assigning values in the constructor, e.g.

    class SavedSearch  {
        constructor() {
            this.id = '';
            this.type = '';
            this.title = '';
            this.createdAt = new Date();
        }
    }
    

    Why? Simple really, using the above plus some JSdoc comments, PHPStorm was able to perform code completion on the properties. Assigning all the vars in one hit was nice, but the inability to code complete the properties, imo, isn't worth the (almost certainly minuscule) performance benefit.

    0 讨论(0)
提交回复
热议问题