【问题标题】:NativeScript extension methodsNativeScript 扩展方法
【发布时间】:2017-03-10 08:24:10
【问题描述】:

是否可以在本机脚本中扩展现有类?通过扩展我的意思是用 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();

【问题讨论】:

    标签: nativescript angular2-nativescript


    【解决方案1】:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-15
      • 2010-09-09
      • 2020-02-29
      • 1970-01-01
      相关资源
      最近更新 更多