我希望能够检测到我正在查看的对象是否是_.template的实例,这与检查 Backbone 模型/集合/ View 的方式相同。
例如:
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
我要诉诸于此:
typeof test == "function"
对于我的情况,这基本上足够好,因为如果我的模板当前是字符串而不是Underscore模板,那么我会将模板包装在_.template中。
但是,我的两个问题-
我想知道当前是否有一种方法来检查_.template的instanceof。
如果不是,那么扩展模板原型(prototype)链以进行此检查是否会非常昂贵?除非速度慢得多,否则这似乎是Underscore中的(次要)故障。
最佳答案
_.template
只是返回一个简单的旧函数,不是任何特别的实例,也不是您应该与new
一起使用的东西,它只是一个简单的函数。
如果我们看看the source(我强烈建议针对此类问题),您会发现_.template
的结构或多或少是这样的:
// A bunch of stuff to convert the template to JavaScript code
// which is combined with some boiler plate machinery and left
// in `source`
// ...
render = new Function(settings.variable || 'obj', '_', source);
template = function(data) { return render.call(this, data, _); };
return template;
因此,您从
_.template(str)
获得的东西只是一个匿名函数,没有建立特殊的原型(prototype)链,唯一与instanceof
一起使用的东西是Function
。在这种情况下,问t instanceof Function
是否真的不是非常有用,我认为这不会做typeof t == 'function'
尚未完成的任何事情。但是,
_.template
will add a source
property返回的函数:因此,您可以通过将
in
与 instanceof
或 typeof
结合起来来加强工作:typeof t === 'function' && 'source' in t
t instanceof Function && 'source' in t
如果
true
来自t
,则两者都应为_.template
(但相反,当然不一定是正确的)。演示:http://jsfiddle.net/ambiguous/a2auU/
至于第二个问题,我想不出当
t()
不是t instanceof T
时,如何使T
和Function
都可以工作(我当然会错过一些显而易见的东西,但是弄乱本机类型通常效果不佳在JavaScript中)。如果您想说:var t = _.template(s);
var h = t.exec(...);
而不是
t(...)
,这将很容易,但是它与有关Underscore模板的所有知识都不兼容。