无法在工厂中使用String.prototype

时间:2016-09-09 12:48:01

标签: javascript angularjs

所以我试图从an answer here

实现一个功能
String.prototype.supplant = function (o) {
     return this.replace(/{([^{}]*)}/g,
         function (a, b) {
             var r = o[b];
             return typeof r === 'string' || typeof r === 'number' ? r : a;
         }
     );
 };

我一直试图把它放在像这样的工厂里

app.factory('Helpers', function() {
  abc = function (o) {
    return supplant(o);
  }

  abc.prototype.supplant = function (o) {
    return this.replace(/{([^{}]*)}/g,
        function (a, b) {
            var r = o[b];
            return typeof r === 'string' || typeof r === 'number' ? r : a;
        }
    );
  };

return abc;
});

我使用过'助手'在我的控制器中,但不断收到错误 "我已经{岁}了!#34; .abc不是一个功能

我需要访问函数abc(),就像答案中所示

 alert("I'm {age} years old!".supplant({ age: 29 }));
 alert("The {a} says {n}, {n}, {n}!".supplant({ a: 'cow', n: 'moo' }));

1 个答案:

答案 0 :(得分:2)

你需要了解复制和粘贴代码之前的工作原理,希望它能够神奇地工作......

在示例中,String.prototype用于扩展 默认 JavaScript String对象(无论引号包围的是String对象),所以以下声明:

String.prototype.supplant = function (o) {
     return this.replace(/{([^{}]*)}/g,
         function (a, b) {
             var r = o[b];
             return typeof r === 'string' || typeof r === 'number' ? r : a;
         }
     );
 };

代码中的所有字符串都可以调用方法supplant()(除了现有的toUppercase()toLowerCase() ...)。

你在角度工厂中所做的事情毫无意义,你不会以这种方式扩展JavaScript的 String 对象,而是创建一个全新的“类型”,所以很明显通过声明:

"a string".supplant()

解释器抱怨它,因为该方法不存在(默认情况下,JavaScript的String接口不实现名为supplant的方法)。

无论如何,由于你使用的是角度,它已经为插值提供了服务:https://docs.angularjs.org/api/ng/service/ $ interpolate

因此,在您的控制器中注入该服务并以这种方式使用它:

$interpolate(stringToInterpolate)(contextScopeForInterpolation);