39

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

5 Answers 5

79

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'
1
  • 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 Commented Jun 25, 2014 at 4: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"
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>

0
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.

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'

Not the answer you're looking for? Browse other questions tagged or ask your own question.