2014-12-08 2 views
1

String에 대한 설명서를보고있는 동안 String.fromCharCode을 참조했습니다. 다른 방법의 대다수와 다른 점은 눈치 채기 전에 .prototype이 없었던 방식입니다. String.prototype.CharCodeAt. 그 사용량은 당신이 String 클래스/개체를 참조하는 데 필요합니다 주어진 자바에서 정적 참조의 그것과 유사해야합니다 예 : 가정합니다.JavaScript에서 정적 메서드와 같은 것을 어떻게 구현합니까?

var str = "foo"; 
var code = str.charCodeAt(0); 
var character = String.fromCharCode(code); // This is the reference I'm talking about 
alert(code); // Output: 102 
alert(character); // Output: f 

내 질문은 그것이 자신의 코드에 String.fromCharCode 같은 스타일로 액세스 할 수 있도록하는 방법을 구현하는 것이 어떻게?

+0

재미 나는 이미이 질문에 대한 답을 찾기 위해 노력하고 그 많은 일을 읽은 및 실패했습니다. 내가 어떻게 든 그것을 놓쳤을 가능성이있다, 내가보고 있어야하는 특정 섹션이 있는가? –

답변

1

JavaScript에서 함수는 1 급 개체입니다. 정적 메서드로 동작하는 메서드 속성을 직접 할당 할 수 있습니다.

function MyObject() {} 
MyObject.static = function() { ... } 

예상대로 작동합니다.

+0

고마워요! 이것은 정확히 내가 찾고 있었던 것이지만 찾을 수 없었습니다. –

0

DZone's ref 카드는 객체 지향 자바 스크립트에 대한 훌륭한 참고 자료를 제공하므로 적극 추천합니다. 관련 단락

정적 멤버에 대한 직접적인 지원은 없습니다. 생성자 함수 은 정적 멤버를 만드는 데 사용됩니다. 정적 멤버는 "this"키워드를 사용하여 에 액세스 할 수 없습니다.

개인 정적 멤버

function Factory(){} 
    // public static method 
    Factory.getType = function(){ 
     return “Object Factory”; 
    }; 

    // public static field 
    Factory.versionId = “F2.0”; 
    Factory.prototype.test = function(){ 
     console.log(this.versionId); // undefined 
     console.log(Factory.versionId); // F2.0 
     console.log(Factory.getType()); // Object Factory 
    } 
    var factory = new Factory(); 
    factory.test(); 

공공 정적 멤버 충분히

var Book = (function() { 
// private static field 
    var numOfBooks = 0; 
// private static method 
    function checkIsbn(isbn) { 
     if (isbn.length != 10 && isbn.length != 13) 
      throw new Error(“isbn is not valid!”); 
    } 

    function Book(isbn, title) { 
     checkIsbn(isbn); 
     this.isbn = isbn; 
     this.title = title; 
     numOfBooks++; 
     this.getNumOfBooks = function() { 
      return numOfBooks; 
     } 
    } 

    return Book; 
})(); 
var firstBook = new Book(“0-943396-04-2”, “First Title”); 
console.log(firstBook.title); // First Title 
console.log(firstBook.getNumOfBooks()); // 1 
var secondBook = new Book(“0-85131-041-9”, “Second Title”); 
console.log(firstBook.title); // First Title 
console.log(secondBook.title); // Second Title 
console.log(firstBook.getNumOfBooks()); // 2 
console.log(secondBook.getNumOfBooks()); // 2 
관련 문제