@bqio
https://bqio.github.io/

Как получить имя класса из объекта в JavaScript?

export default class Background {
  constructor ({ name, sprite}) {
    this.name = name
    this.sprite = sprite
    this.src = null
    this.width = 720
    this.height = 1280
    this.x = 0
    this.y = 0
  }
}

let defaultBg1 = new Background({
  name: 'Background',
  sprite: 'Default'
})

if (typeof defaultBg1 == 'Background') // ???
  • Вопрос задан
  • 1322 просмотра
Решения вопроса 1
0xD34F
@0xD34F Куратор тега JavaScript
if (typeof defaultBg1 == 'Background') // ???

Это по-другому делается (с известными ограничениями - у null и undefined свойств не бывает, попытка обратиться к конструктору в их случае приведёт к TypeError; кроме того, instanceof проверяет всю цепочку прототипов, т.е., например, [ 1, 2, 3 ] одновременно и instanceof Array, и instanceof Object):

if (defaultBg1 instanceof Background)
// или
if (defaultBg1.constructor === Background)
// или
if (defaultBg1.constructor.name === 'Background')

А вообще, можно соорудить такой костыль:

const type = x => x == null ? `${x}` : x.constructor.name;

type() // 'undefined'
type(null) // 'null'
type(true) // 'Boolean'
type(69) // 'Number'
type('hello, world!!') // 'String'
type(/./) // 'RegExp'
type([ 187 ]) // 'Array'
type({ z: 666 }) // 'Object'
type(document) // 'HTMLDocument'
type(document.querySelectorAll('div')) // 'NodeList'
type(new class XXX {}) // 'XXX'
type(type) // 'Function'
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы