I would like to be able to detect if an object I'm looking at is an instance of _.template, the same way I can check for Backbone Models/Collections/Views.
var newView = new Backbone.View(); newView instanceof Backbone.View //true //How I usually use template var test = _.template("test"); test instanceof _.template //false //When I would actually expect a successful instanceof check var test2 = new _.template("test"); test2 instanceof _.template //false
I'm resorting to this instead:
typeof test == "function"
This is basically good enough for my circumstances, since I'm just wrapping my template in _.template if it's currently a string instead of an Underscore template.
However, my 2 questions -
I'm wondering if there's a way to check instanceof _.template, currently.
If not, is it prohibitively expensive to extend the template Prototype chain to allow this check? Unless it's much slower, this seems like a (minor) fault in Underscore.
_.template simply returns a plain old function, not an instance of anything in particular and not something that you're supposed to use with
new, it is just a simple function.
If we have a look at the source (which I strongly recommend for questions like this), you'll see that the structure of
_.template is more or less like this:
So the thing you get back from
_.template(str) is just an anonymous function, there's no special prototype chain set up and the only common thing to use with
Function. Asking if
t instanceof Function really isn't terribly useful in this case, I don't think that will do anything that
typeof t == 'function' isn't doing already.
_.template will add a
source property to the returned function:
The source property is available on the compiled template function for easy precompilation.
typeof t === 'function' && 'source' in t t instanceof Function && 'source' in t
Both of those should be
t came from
_.template (but the converse is, of course, not necessarily true).
As far as the second question goes, I can't think of how you can have
t instanceof T both work when
T is not
var t = _.template(s); var h = t.exec(...);
t(...) then it would be easy but it would be incompatible with everything that knows about Underscore templates.