Javascript:总是在执行上下文中执行函数 [英] Javascript: always execute function in execution context

查看:136
本文介绍了Javascript:总是在执行上下文中执行函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  var templatize = function(string){
return function字符串){
return string.replace(/{{(*))}/g,function(pattern,match){
value = this [match];
if ){
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 方法可以通过namedscope访问,但是, templatize 的当前上下文不是



像调用 $。proxy(templatize,this)(W​​e are {{foo}} and {但是我想实现这一点,而不需要这样做,但是我想要实现这个目标,而不是{{crazy}})调用$ .proxy()(最好没有任何jQuery),这样上下文就自动转移到执行一个。



我努力使用 .call() .apply()和其他闭包,但我想我在互联网上的某个地方读到这是可能的。感谢

解决方案

为什么不传递包含视图变量的对象?将更清晰,然后可能显示您的视图中的任何现有变量。

  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);
}


I wrote this fast-templating function:

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);
}

Which does this:

var foo = "bar", bar = "foo";
templatize("We are {{foo}} and {{bar}}, but not {{crazy}}"); // "We are bar and foo but not {{crazy}}"

I'm quite happy with this except that I have scoping problem. For sure, the templatize method will be accessible through namedscope, but then, the current context of execution of templatize is not accessible in my function automatically.

Something like calling $.proxy(templatize, this)("We are {{foo}} and {{bar}}, but not {{crazy}}") should work, right?

But I'd like to achieve this without needing to call $.proxy() (and without any jQuery preferably) so that context is automatically transfered to the execution one.

I'm struggling with .call(), .apply(), and other closures, but I think I read somewhere over the internet that it was possible. Thanks

解决方案

why don't you pass an object containing the view variables? would be cleaner then potentially displaying any existing variable in your view.

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);
}

这篇关于Javascript:总是在执行上下文中执行函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆