ES6 class variable alternatives

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

    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.

提交回复
热议问题