使用函数构造函数时了解UnderScore.js

时间:2013-08-22 07:25:49

标签: algorithm underscore.js

此时此刻,我将了解underscore.js的这个分块代码是如何流动的,

 var render = new Function(settings.variable || 'obj', '_', source);

我喜欢看到它与我的示例代码相比有多么明显,我可以简单地写出来。

 var render = new Function("a", "b", "return a + b");

然后就会变成,

 var render = function (a, b) {
    return a + b;
 };

有人可以帮我描述它是如何流动的吗? (对不起,如果我的英语不好。)


来自评论员,我想问一下source如何在我的简单函数中描述或流动,它总结了两个参数。

显然,我可以理解,source应该由中组成 a settings.variable || 'obj'b
'_'run

但是,我不知道,
source部分b中的哪种运算符


当我学会了自己时,真正的问题在于'_' // JavaScript micro-templating, similar to John Resig's implementation. // Underscore templating handles arbitrary delimiters, preserves whitespace, // and correctly escapes quotes within interpolated code. _.template = function(text, data, settings) { settings = _.defaults(settings || {}, _.templateSettings); // Compile the template source, taking care to escape characters that // cannot be included in a string literal and then unescape them in code // blocks. var source = "__p+='" + text .replace(escaper, function(match) { return '\\' + escapes[match]; }) .replace(settings.escape || noMatch, function(match, code) { return "'+\n_.escape(" + unescape(code) + ")+\n'"; }) .replace(settings.interpolate || noMatch, function(match, code) { return "'+\n(" + unescape(code) + ")+\n'"; }) .replace(settings.evaluate || noMatch, function(match, code) { return "';\n" + unescape(code) + "\n;__p+='"; }) + "';\n"; // If a variable is not specified, place data values in local scope. if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; source = "var __p='';" + "var print=function(){__p+=Array.prototype.join.call(arguments, '')};" +"\n"+source + "return __p;\n"; var render = new Function(settings.variable || 'obj', '_', source); if (data) return render(data, _); var template = function(data) { return render.call(this, data, _); }; // Provide the compiled function source as a convenience for build time // precompilation. template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}'; return template; }; ,可能是我需要很多时间,但这是我所谈论的完整代码块。

{{1}}

0 个答案:

没有答案