是否可以在本机脚本中扩展现有类?通过扩展我的意思是它在C#术语中,例如不是继承,而是“注入”方法到现有的类,并在原始类的实例上调用该方法。
C#扩展方法:
public static class MyExtensions
{
public static int WordCount(this String str)
{
return str.Split(new char[] { ' ', '.', '?' },
StringSplitOptions.RemoveEmptyEntries).Length;
}
}
string s = "Hello Extension Methods";
int i = s.WordCount();
答案 0 :(得分:2)
JavaScript允许您更改任何对象的原型;所以你可以这样做:
String.prototype.wordCount = function() {
var results = this.split(/\s/);
return results.length;
};
var x = "hi this is a test"
console.log("Number of words:", x.wordCount());
并输出Number of words: 5
。
您还可以使用Object.defineProperty添加属性(而不是函数),如下所示:
Object.defineProperty(String.prototype, "wordCount", {
get: function() {
var results = this.split(/\s/);
return results.length;
},
enumerable: true,
configurable: true
});
var x = "hi this is a test"
console.log("Number of words:", x.wordCount); // <-- Notice it is a property now, not a function