class или static внутри if
Мне нужно получить либо
class BoldBlot extends Inline {}
Либо
class BoldBlot extends Inline {
static create(value) {
let node = super.create();
node.setAttribute('url', value);
return node;
}
static formats(node) {
return node.getAttribute('url');
}
}
Но проблема в том что если я засовываю if внутрь class BoldBlot
то не видит static
, а если снаружи class BoldBlot
то не видит сам BoldBlot
И как мне тогда это сделать?
Ответы (2 шт):
Автор решения: Денис Степанов
→ Ссылка
const BoldBlot = ((flag) => {
if (flag) {
return class BoldBlot extends Object {};
} else {
return class BoldBlot extends Array {};
}
});
const arr = new (BoldBlot(false))(2,4,5,6);
const obj = new (BoldBlot(true));
console.log(arr);
console.log(obj);
Автор решения: OPTIMUS PRIME
→ Ссылка
class Test {
static moo() {
// ...
}
}
↑ Эквивалентно ↓ (* почти, у первого нет prototype)
class Test {}
Test.moo = function() {
"use strict";
// ...
}
Поэтому можно так:
class BoldBlot extends Inline {}
if (smth) {
BoldBlot.create = function(value) { // <-- static create(value) {
let node = super.create();
node.setAttribute('url', value);
return node;
};
BoldBlot.formats = function(node) { // <-- static formats(node) {
return node.getAttribute('url');
};
}
Если действие происходит внутри какой-то функции, можно наоборот, if (!smth) return; и дальше объявлять методы без дополнительной вложенности.