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

자바 스크립트는 어떤 객체의 프로토 타입을 변경할 수 있습니다; 그래서 당신은 할 수있다 :

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 
관련 문제