38

I use console.log() a lot, especially in combination with Ember.inspect(). But there's one thing I miss:

How can I find out the type of an object (Class)?

For example: Getting something like <Sandbox.ApplicationController:ember288> when inspecting Ember.get("controller")?

kraftwer1
  • 5,253
  • 10
  • 36
  • 54

5 Answers5

78

If you just want the model name (for example app/models/comment.js has the model name comment), you can use thing.constructor.modelName.

For example:

var aComment = this.get('store').createRecord('comment');
aComment.get('constructor.modelName') // => 'comment'
real_ate
  • 10,861
  • 3
  • 27
  • 48
Kerrick
  • 7,420
  • 8
  • 40
  • 45
  • When I use that field in the template I get this error: Uncaught Error: Something you did caused a view to re-render after it rendered but before it was inserted into the DOM – freakTheMighty Jun 25 '14 at 04:15
24

I understand you are looking for a string for debugging purposes, but I originally came to this question wanting to know specifically how to get the type of the object, not a string describing the object.

Using the built in Javascript property constructor will yield the class used to construct the instance. For example you could do:

person = App.Person.create();
person.constructor // returns App.Person
person.constructor.toString() // return "App.Person"
David Monagle
  • 1,701
  • 16
  • 19
18

If you get Class, you can usually call toString() (or as a shortcut concat an empty string + '') to get something like <Sandbox.ApplicationController:ember288>

Luke Melia
  • 8,389
  • 33
  • 41
1

Another useful feature (in chrome) is the dir command.

dir(App.User)

This will give you the full object information, rather than just the name.

Gevious
  • 3,214
  • 3
  • 21
  • 42
1

Be aware that some of these answers suggested here only work in development. Once your code is in production most of those methods / class names will get minified.

import Model from '@ember-data/model';

export default class Animal extends Model {
  // ...
}

So in development:

const model = this.store.createRecord('animal');
model.constructor.name // returns Animal

in production:

const model = this.store.createRecord('animal');
model.constructor.name // returns 'i' (or any other single letter).

To avoid this, use constructor.toString()

const model = this.store.createRecord('animal');
model.constructor.toString() // returns 'model:animal'
esbanarango
  • 1,634
  • 15
  • 17