[英]Javascript: always execute function in execution context
我写了这个快速模板函数:
var templatize = function(string) {
return function (string) {
return string.replace(/{{(.*?)}}/g, function(pattern, match) {
value = this[match];
if (value) {
return value;
} else {
return pattern;
}
});
}.call(this, string);
}
这样做:
var foo = "bar", bar = "foo";
templatize("We are {{foo}} and {{bar}}, but not {{crazy}}"); // "We are bar and foo but not {{crazy}}"
我对此感到很满意,除了遇到范围问题。 当然,可以通过namedscope访问templatize
方法,但是,在我的函数中无法自动访问templatize
的当前执行上下文。
像调用$.proxy(templatize, this)("We are {{foo}} and {{bar}}, but not {{crazy}}")
应该起作用,对吗?
但是我想实现这一目标,而无需调用$ .proxy()(最好没有任何jQuery),以便上下文自动转移到执行代码中。
我挣扎.call()
.apply()
和其他关闭,但我想我在这是有可能的互联网读的地方。 谢谢
您可以避免使用jQuery来做到这一点:
var templatize = function(string) {
var me = this; // the data source
return string.replace(/{{(.*?)}}/g, function (full, key) {
// "this" refers to the string itself
return me[key] || full;
});
}
如果要使用jQuery.proxy()
,请包装替换函数:
var templatize = function(string) {
return string.replace(/{{(.*?)}}/g, jQuery.proxy(function (full, key) {
// "this" now refers permanently to the data source
return this[key] || full;
}, this));
}
在这两种情况下,都可以使用call
将数据源绑定this
:
templatize.call({ hello: 'Hi!' }, '{{hello}}');
您可以通过编译模板以进行重用来进行优化:
function compile(tpl) {
var i = -1, tmp = [];
tpl = tpl.split(/{{([^{}]+)}}/);
while (++i < tpl.length) {
if (i % 2) tmp.push('this["' + tpl[i] + '"]');
else if (tpl[i]) tmp.push('"' + tpl[i].replace(/"/g, '\\"') + '"');
}
return new Function(
'return [' + tmp.join() + '].join("");'
);
}
用法示例:
var tpl = compile('{{hello}} {{hello}}');
tpl.call({ hello: 'Hi!' }); // "Hi! Hi!"
tpl.call({ hello: 'Yo!' }); // "Yo! Yo!"
对于上面的示例,这是compile
返回的函数:
function () {
return [this["hello"]," ",this["hello"]].join("");
}
请注意,您也可以使用数组:
var tpl = compile('{{1}} {{0}}');
tpl.call(['a', 'b']); // "b a"
性能测试: http : //jsperf.com/template-compiling 。
为什么不传递包含视图变量的对象? 会更清洁,然后可能在视图中显示任何现有变量。
var templatize = function(string, variables) {
return function (string) {
return string.replace(/{{(.*?)}}/g, function(pattern, match) {
value = variables[match];
if (value) {
return value;
} else {
return pattern;
}
});
}.call(this, string);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.