2017-03-10 135 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