NativeScript扩展方法
是否可以在本机脚本中扩展现有类?在C#术语中,我所说的扩展是指它,例如,不是继承,而是将方法“注入”到现有类中,并在原始类的实例上调用该方法 C#扩展方法:NativeScript扩展方法,nativescript,angular2-nativescript,Nativescript,Angular2 Nativescript,是否可以在本机脚本中扩展现有类?在C#术语中,我所说的扩展是指它,例如,不是继承,而是将方法“注入”到现有类中,并在原始类的实例上调用该方法 C#扩展方法: public static class MyExtensions { public static int WordCount(this String str) { return str.Split(new char[] { ' ', '.', '?' },
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();
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());
它将输出字数:5
您还可以使用添加属性(而不是函数),如下所示:
Object.defineProperty(String.prototype,“wordCount”{
get:function(){
var results=this.split(/\s/);
返回结果。长度;
},
可枚举:正确,
可配置:true
});
var x=“嗨,这是一个测试”
console.log(“字数:”,x.wordCount);// 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());
它将输出字数:5
您还可以使用添加属性(而不是函数),如下所示:
Object.defineProperty(String.prototype,“wordCount”{
get:function(){
var results=this.split(/\s/);
返回结果。长度;
},
可枚举:正确,
可配置:true
});
var x=“嗨,这是一个测试”
log(“字数:”,x.wordCount)//