JS & ES6: Access static fields from within class
Asked Answered
G

3

13

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)?

Gamma answered 11/12, 2015 at 9:28 Comment(6)
You cannot. It's not defined until the closing } on the last lineAshely
in a method you could do MyStyle.Color.mainDark.Masterwork
That's not ES6. That's some weird experimental (ES7-proposed) property intialisers.Glennglenna
sounds like either a duplicate of es6 call static methods/Call static method within a class or Self-references in object literal declarationsGlennglenna
@Glennglenna those are stage-1, so not that weird :-)Ashely
@zerkms: Weird in the sense that I really dislike the proposed operator(s). Apparently the choice of the "assignment operator" causes quite some confusion here.Glennglenna
Q
12

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.

Quicktempered answered 11/12, 2015 at 10:2 Comment(2)
Is there something like self.Color.mainDark so that one can omit repeating the name of the class?Cossack
@Ionix I don't think soQuicktempered
A
1

indeed, this.constructor points to the class hierarchy.

take a look:

class Some {
    static static_elem = 'elem';
    constructor(param) {
         
       console.log( Some.static_elem, param);
        console.log( this.constructor.static_elem, param);
    }
};

var some = new Some('some');

class SomeOther extends Some {
    constructor(param) {
        super(param);
        console.log( Some.static_elem, param);
        console.log( SomeOther.static_elem, param);
        console.log( this.constructor.static_elem, param);
    }
};

var someother = new SomeOther('someother');
Allege answered 27/5, 2023 at 7:49 Comment(0)
E
0
'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

Entrepreneur answered 11/12, 2015 at 9:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.