Monkey 将函数修补到现有类中
有时能够使用新函数扩展类是有用的。例如,假设应该将字符串转换为驼峰大小写字符串。所以我们需要告诉 TypeScript,String
包含一个名为 toCamelCase
的函数,它返回一个 string
。
interface String {
toCamelCase(): string;
}
现在我们可以将此功能修补到 String
实现中。
String.prototype.toCamelCase = function() : string {
return this.replace(/[^a-z ]/ig, '')
.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, (match: any, index: number) => {
return +match === 0 ? "" : match[index === 0 ? 'toLowerCase' : 'toUpperCase']();
});
}
如果加载了 String
的这个扩展,它可以像这样使用:
"This is an example".toCamelCase(); // => "thisIsAnExample"