ES6 class variable alternatives

前端 未结 15 2402
长发绾君心
长发绾君心 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: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.

提交回复
热议问题