2017-03-10 44 views
0

ネイティブスクリプトで既存のクラスを拡張することはできますか?私はそれをC#の用語で意味しています。継承しませんが、既存のクラスにメソッドを挿入し、元のクラスのインスタンスでそのメソッドを呼び出します。NativeScript拡張メソッド

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

答えて

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