【发布时间】:2014-01-20 01:06:44
【问题描述】:
我写了这个快速模板函数:
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}}"
我对此很满意,只是我遇到了范围界定问题。当然,templatize 方法可以通过命名作用域访问,但是,templatize 的当前执行上下文无法在我的函数中自动访问。
调用$.proxy(templatize, this)("We are {{foo}} and {{bar}}, but not {{crazy}}") 之类的方法应该可以,对吧?
但我想在不需要调用 $.proxy() 的情况下实现这一点(最好不使用任何 jQuery),以便上下文自动转移到执行。
我正在为.call()、.apply() 和其他关闭而苦苦挣扎,但我想我在互联网的某个地方读到它是可能的。谢谢
【问题讨论】:
-
你检查过小胡子或车把的源代码吗?
-
Javascript OO reference this 的可能重复项
标签: javascript scope closures