javascript - 检测 instanceof Underscore 模板

标签 javascript templates backbone.js underscore.js prototypal-inheritance

我希望能够检测我正在查看的对象是否是 _.template 的实例,就像我可以检查主干模型/集合/ 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 中。

但是,我的 2 个问题 -

我想知道目前是否有检查 instanceof _.template 的方法。

如果不是,扩展模板原型(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 一起使用的东西code> 是函数。询问 t instanceof Function 在这种情况下是否真的不是很有用,我认为这不会做 typeof t == 'function' 没有做的任何事情已经。

然而,_.template will add a source property到返回的函数:

The source property is available on the compiled template function for easy precompilation.

所以你可以通过组合 in 来收紧事情与 instanceoftypeof :

typeof t === 'function' && 'source' in t
t instanceof Function  && 'source' in t

如果 t 来自 _.template,那么这两个都应该是 true(当然,反之不一定为真) .

演示:http://jsfiddle.net/ambiguous/a2auU/

至于第二个问题,我想不出当 T 不是 Function(当然我可能遗漏了一些明显的东西,但在 JavaScript 中乱用原生类型通常效果不佳)。如果你想说:

var t = _.template(s);
var h = t.exec(...);

而不是 t(...) 那么它会很容易,但它与所有关于 Underscore 模板的知识都不兼容。

关于javascript - 检测 instanceof Underscore 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18410421/

相关文章:

javascript - 类型错误:无法读取 JavaScript 中未定义的属性 'push'

javascript - jQuery 整体平滑滚动而不是 DIV

javascript - Phonegap 无法检测到 index.js

c++ - 如何为模板类重载 % 运算符?

javascript - jQuery .click() 不会从 Mustache.js 模板中的 <a> 触发

javascript - 如何将可点击的链接/对话框添加到 Backbone.js JST EJS 文件

c++ - 如何在不使用继承的情况下将模板实例化为 'rename'?

javascript - 用主干覆盖同步值的简单方法

javascript - 主干 - 复制粘贴网址

json - 多个模型子类的 Backbone.js 集合