JS & ES6: Access static fields from within class

后端 未结 2 645
无人共我
无人共我 2020-12-10 15:52

In ES6, given the following example:

export default class MyStyle extends Stylesheet {
   static Color = {
      mainDark: \'#000\'
   }
   static Comp = {
          


        
相关标签:
2条回答
  • 2020-12-10 15:54

    You can access it as you would expect, however if I recall there were some issues when using Babel and exporting the class immediately, so export after defining the class if you're having problems:

    class MyStyle extends Stylesheet {
       static Color = {
          mainDark: '#000'
       }
    
      someMethod() {
        console.log(MyStyle.Color.mainDark);
      }
    }
    
    export default MyStyle;
    

    You can read more about the Babel issue in an answer Marian made on a similar question, which is supposedly fixed in Babel 6.2.1.

    0 讨论(0)
  • 2020-12-10 15:56
    'use strict';
    
     class User {
       constructor(firstName, lastName) {
       this.firstName = firstName;
       this.lastName = lastName;
     }
    
     static createGuest() {
        return new User("guest", "site");
       }
     };
    
     let user = User.createGuest();
    
      alert( user.firstName ); // guest
    
      alert( User.createGuest ); // createGuest ... (function)
    

    And const:

    'use strict';
    
    class Menu {
     static get elemClass() {
       return "menu"
     }
    }
    
    alert( Menu.elemClass ); // menu
    

    use call to context object --- this

    ES6 - Call static method within a class

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