Get the model type for a passed in backbone.js mod

2019-06-16 15:53发布

问题:

How do I retrieve the model name for a backbone.js model instance?

For example:

var Topic = Backbone.Model.extend({

})
var topic = new Topic({ type: 'question' })

var doSomethingWithTopic = function(topic) {
  // check if passed in topic is of type Topic
  // something like topic.constructor.name === 'Topic'
}

doSomethingWithTopic(topic)

I realize I may be blurring the line between a backbone.js model and a class, so I am open to other ways of going about this if needed.

回答1:

Use the instanceof operator.

var doSomethingWithTopic = function(topic) {
  if( topic instanceof Topic ) {
    // do something with topic
  }
}