Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   ES6. Class constructor question (https://javascript.ru/forum/misc/81424-es6-class-constructor-question.html)

voraa 26.11.2020 10:49

Есть еще один способ добраться из базового класса, до класса самого верхнего наследника.
this.constructor
Причем, это прокатывает даже в определении полей, в отличие от new.target, который работает только непосредственно в конструкторе

/**
 * @abstract
 */
class AbstractHttpService {
    baseRouteName = this.constructor.baseRouteName;
      
    constructor(baseRouteName) {
        if (baseRouteName)  this.baseRouteName = baseRouteName;
    }
}
  
class ProductsHttpService extends AbstractHttpService {
    static baseRouteName = 'product';
}
 
let x = new ProductsHttpService ()
console.log (x.baseRouteName)

Alexandroppolus 26.11.2020 12:29

может, так?
class AbstractHttpService {
    get baseRouteName() {
        return '';
    }
}
  
class ProductsHttpService extends AbstractHttpService {
    get baseRouteName() {
        return 'product';
    }
}
 
let x = new ProductsHttpService ()
console.log (x.baseRouteName)

voraa 26.11.2020 13:02

Ну если сеттера не нужно.
А если нужен, то надо где то хранить значение. И опять проблема, как установить начальное.


Часовой пояс GMT +3, время: 22:15.