Javascript Can';t让String.prototype在工厂工作
所以我试图从一个 我一直想把这个放在这样的工厂里Javascript Can';t让String.prototype在工厂工作,javascript,angularjs,Javascript,Angularjs,所以我试图从一个 我一直想把这个放在这样的工厂里 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];
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;
});
我在控制器中使用了“Helpers”,但不断出现错误,如
“我{age}岁!”abc不是一个函数
我需要访问函数abc(),就像答案中所示
alert("I'm {age} years old!".supplant({ age: 29 }));
alert("The {a} says {n}, {n}, {n}!".supplant({ a: 'cow', n: 'moo' }));
在复制和粘贴代码之前,您需要了解事情是如何工作的,希望它能神奇地工作 在本例中,
String.prototype
用于扩展defaultJavaScript字符串对象(任何被引号包围的对象都是字符串对象),因此在以下声明之后:
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;
}
);
};
代码中的所有字符串都可以调用方法replacement()
(除了现有的toUppercase()
,toLowerCase()
…)
您在angular factory中所做的一切毫无意义,您不是以这种方式扩展JavaScript的字符串对象,而是创建了一个全新的“类型”,显然是通过声明:
"a string".supplant()
解释器对此表示不满,因为该方法不存在(默认情况下,JavaScript的字符串接口不实现名为replacement
)的方法)
无论如何,由于您使用的是angular,它已经提供了插值服务:$interpolate
因此,将该服务注入控制器并使用它,方法如下:
$interpolate(stringToInterpolate)(contextScopeForInterpolation);
在复制和粘贴代码之前,您需要了解事情是如何工作的,希望它能神奇地工作 在本例中,
String.prototype
用于扩展defaultJavaScript字符串对象(任何被引号包围的对象都是字符串对象),因此在以下声明之后:
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;
}
);
};
代码中的所有字符串都可以调用方法replacement()
(除了现有的toUppercase()
,toLowerCase()
…)
您在angular factory中所做的一切毫无意义,您不是以这种方式扩展JavaScript的字符串对象,而是创建了一个全新的“类型”,显然是通过声明:
"a string".supplant()
解释器对此表示不满,因为该方法不存在(默认情况下,JavaScript的字符串接口不实现名为replacement
)的方法)
无论如何,由于您使用的是angular,它已经提供了插值服务:$interpolate
因此,将该服务注入控制器并使用它,方法如下:
$interpolate(stringToInterpolate)(contextScopeForInterpolation);
app.factory
做什么?app.factory做什么?