【问题标题】:Using function context/variables without function arguments使用没有函数参数的函数上下文/变量
【发布时间】:2021-05-09 11:43:10
【问题描述】:

我正在尝试实现自己的 template literals 功能(出于教育目的),但我不明白它是如何工作的。

我的想法是用函数扩展String.prototype,这将eval 字符串内的每个${} 序列。问题是我的新函数不知道上下文(字符串中的变量)。以下是我认为它应该如何工作:

String.prototype.smart_eval = function() { /* find all ${} and eval them */ }

function some_function() {
  let a = 1;
  let b = 2;
  return 'A is ${a}, B is ${b}, the sum is ${a + b}'.smart_eval()
}

这将导致Uncaught ReferenceError: a is not defined,因为ab 属于some_function(),而不是smart_eval()。有没有不使用函数参数或.call() / .apply() 的优雅方法来解决这个问题?

【问题讨论】:

    标签: javascript eval template-literals


    【解决方案1】:

    所以...看来我想要一些东西,那是不可能的。为了尽可能顺利地解决这个问题,我的第一个想法是类似 Python 的函数 format我不认为这段代码是 100% 有效的解决方案,但也许有人会发现它有用。

    String.prototype.format=function(values) {
      let s = this;
      let r = '';
      for (let i = 0; i < s.length; i++) {
        if (s[i] == '{') {
          for (let t = i+1; t < s.length; t++) {
            if (s[t] == '}') {
              let d = s.substring(i + 1, t);
              try { d = parseInt(d) }
              catch(err) { d = false } 
              finally {
                if (d !== false) {
                  if (values.length >= d + 1) { r += values[d]; i = t; break; }
                  else { throw new ReferenceError('Literal is out of values range.') }
                }
              }
            }
          }
        } else {
          r += s[i] || ''
        }
      }
      return r
    }
    

    例子:

    'Hello {0}!'.format(['there']) // output: 'Hello there!'
    'G{0}n{0}ral K{0}n{1}.'.format(['e', 'obi']) // output: 'General Kenobi.'
    

    如果您不需要IE11支持和其他一些浏览器,您可以在函数定义中使用rest parameters

    String.prototype.format=function(...values) {
    

    并以更方便的方式调用它(无需将参数包装到数组中):

    '{1} wanna {0}? Let\'s {0}!'.format('play', 'You') // output: 'You wanna play? Let's play!'
    

    【讨论】:

    猜你喜欢
    • 2012-07-17
    • 1970-01-01
    • 2018-02-15
    • 1970-01-01
    • 2011-12-24
    • 2020-01-16
    • 2012-10-04
    • 1970-01-01
    • 2014-05-25
    相关资源
    最近更新 更多