ES6 class variable alternatives

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

提交回复
热议问题