Javascript:始终在执行上下文中执行函数

标签 javascript scope closures

我编写了这个快速模板函数:

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 将数据源绑定(bind)到 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 .

关于Javascript:始终在执行上下文中执行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20885411/

相关文章:

javascript - apollo 服务器突变中无法使用 console.log() 函数

javascript - 移动和桌面 View 的 Angular Controller 继承

javascript - 如何从 onclick() 按钮获取值以输入 jquery

php - 是否可以在 PHP 中访问外部局部变量?

javascript - 如何在更新数据库记录时使用 $watch 查看更改

javascript - 同一页面中有多个计数器来统计每个用户的时间。

C++ "::"没有类名

javascript - 使用闭包存储和检索数据

Swift 3 嵌套函数与闭包

swift - 内部闭包的捕获列表是否需要将 `self` 重新声明为 `weak` 或 `unowned`?