JS & ES6: Access static fields from within class

不想你离开。 提交于 2019-12-01 02:29:57

问题


In ES6, given the following example:

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

How can I access Color.mainDark (the static field)?


回答1:


I assume you mean ES.next (probably using babel stage-0) as klaemo said 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.




回答2:


'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



来源:https://stackoverflow.com/questions/34220098/js-es6-access-static-fields-from-within-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!