ES6 class / instance properties

前端 未结 1 716
春和景丽
春和景丽 2020-12-09 06:50

This is going to be a relatively long question, but one I would really like to understand. Final question formulated at the bottom of the question.

I have read the

相关标签:
1条回答
  • 2020-12-09 07:19

    I don't get this; static variables in a class based language would appear to serve the same purpose as properties defined on the prototype in JS.

    No, static variables are more like properties defined on the constructor. Variables on the prototype would be closer to instance variables, but they’re not nearly as useful because they’re shared between instances. (So if you modify a mutable property on the prototype, it will be reflected in all other instances of that type.)

    This also answers your other questions, I think, but to recap:

    • variables on the prototype are not like static variables in that they appear to belong to every instance rather than just the class

    • variables on the prototype are not like instance variables in that each instance of the class doesn’t have its own instance of the variable

    • therefore, variables on the prototype are not that useful and they should be assigned to in the constructor (instance variables) or assigned to the constructor (class variables)

    • they’re also properties, not variables

    And a non-ES6-sugared example:

    function Something() {
        this.instanceProperty = 5;
    }
    
    Something.staticProperty = 32;
    
    Something.prototype.prototypeProperty = 977;
    
    var s = new Something();
    console.log(s.instanceProperty); // 5
    console.log(s.prototypeProperty); // 977? If you want a class property,
                                      // this is not what you want
    console.log(s.staticProperty); // undefined; it’s not on the instance
    console.log(Something.staticProperty); // 32; rather, it’s on the class
    console.log(Something.prototypeProperty); // undefined; this one isn’t
    
    0 讨论(0)
提交回复
热议问题