NativeScript 扩展方法

NativeScript extension methods

是否可以在本机脚本中扩展现有的 class?通过扩展我的意思是 C# 术语,例如不是继承,而是对现有 class 的 'inject' 方法,并在原始 class.

的实例上调用该方法

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();

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