2015-01-26 6 views
0

저자 이름 (문자열)을 이름과 성으로 나눈 문자열 메서드 String.prototype.splitName()이 있습니다. 문 var name = authorName.splitname();은 문자 namename.first = "..."name.last = "..." (문자열은 값이 name입니다.)으로 반환합니다.JavaScript의 문자열 서브 클래 싱

최근에 나는은 (는) 공공 문자열() 클래스의 방법으로 splitName()을 가지고 현명하지 못한 것을 들었다,하지만 난 문자열의 개인 서브 클래스를 만드는 대신 공용 클래스의 (하위 클래스를 확장해야) 내 기능. 내 질문은 : 어떻게 새 서브 클래스에 authorName을 할당 한 후 name = authorName.splitname(); 여전히 유효한 문이되도록 문자열의 서브 클래 싱을 수행합니까? 그리고 어떻게 문자열의 새로운 private 서브 클래스에 authorName을 할당하겠습니까?

+5

하지 마십시오. 자신 만의 객체를 만들거나 함수를 사용하십시오. [Maintainable JavaScript : 소유하지 않은 객체를 수정하지 마십시오.] (http://www.nczonline.net/blog/2010/03/02/maintainable-javascript-dont-modify-objects-you-down-own) /)/ –

+0

[이 요지] (https://gist.github.com/NV/282770)를 살펴볼 수 있습니다. –

+0

이것은 끔찍한 것 같습니다. String의이 "서브 클래스"는 변경 가능하며, 길이는 길이와 동일하지 않을 수도 있습니다. –

답변

2

에 의해 영감을 받았습니다. https://gist.github.com/NV/282770 나는 내 자신의 질문에 대답합니다. 아래의 ECMAScript-5 코드에서 객체 클래스 "StringClone"을 정의합니다. (1) 클래스 은 네이티브 클래스 "문자열"에서 모든 속성을 상속받습니다. 의 인스턴스 "StringClone"은 "String"메서드를 트릭없이 적용 할 수없는 개체입니다. 문자열 메서드가 적용되면 JavaScript는 "toString()"및/또는 "valueOf()"메서드를 호출합니다. (2)에서 이러한 메서드를 재정 의하여 "StringClone"클래스의 인스턴스가 문자열처럼 동작하도록 만들어집니다. 마지막으로 인스턴스의 속성 "길이"가 읽기 전용이되므로 (3)은 이 도입 된 이유입니다.

// Define class StringClone 
function StringClone(s) { 
    this.value = s || ''; 
    Object.defineProperty(this, 'length', {get: 
       function() { return this.value.length; }}); //(3) 
}; 
StringClone.prototype = Object.create(String.prototype);  //(1) 
StringClone.prototype.toString = StringClone.prototype.valueOf 
           = function(){return this.value}; //(2) 

// Example, create instance author: 
var author = new StringClone('John Doe'); 
author.length;   // 8 
author.toUpperCase(); // JOHN DOE 

// Extend class with a trivial method 
StringClone.prototype.splitName = function(){ 
    var name = {first: this.substr(0,4), last: this.substr(4) }; 
    return name; 
} 

author.splitName().first; // John 
author.splitName().last; // Doe