2010-05-12 5 views
2

JavaScript의 메서드로 어려움을 겪고 있습니다.내부 개체에서 자바 스크립트 메서드 호출

obj = function(){ 
    this.getMail = function getMail(){ 
    } 
//Here I would like to run the get mail once but this.getMail() or getMail() wont work 
    } 


var mail = new obj(); 
mail.getMail(); 

어떻게 내가 객체의 내부 및 외부

감사에서 모두 실행할 수있는 방식으로 방법을해야합니까

답변

4

당신은 함수처럼, 한 번만 이름을 사용 정의 할 때 이 :

obj = function(){ 
    this.getMail = function(){ 
    alert("bob"); 
    } 
} 

이제 you can see a working example here, 거기에 this.getMail()를 사용할 수 있습니다.

+0

감사합니다, 정말 유용한 도구. – John

0

개체에 대한 강력한 정의를 작성하는 것이 좋습니다. 프로토 타입을 작성한 다음 두 개 이상 필요하면 인스턴스를 만들 수 있습니다. 아래에 프로토 타입을 작성하고, 서로를 호출하는 메소드를 추가하고, 오브젝트를 인스턴스화하는 방법을 보여줍니다.

OBJ = 함수() {} 당신이 가서 여기 빈 개체

obj.prototype.getMail = function() { 
//this is a function on new instances of that object 
    //whatever code you like 
    return mail; 
} 

obj.prototype.otherMethod = function() { 
//this is another function that can access obj.getMail via 'this' 
    this.getMail(); 
} 

var test = new obj; //make a new instance 
test.getMail();  //call the first method 
test.otherMethod(); //call the second method (that has access to the first) 
+0

감사합니다. 프로토 타입에 익숙하지 않습니다. 제가 확인하겠습니다 – John

0

을 정의 // : 링크에 대한

var obj = function() { 

    function getMail() { 
     alert('hai!'); 
    } 

    this.getMail = getMail; 
    //Here I would like to run the get mail once but this.getMail() or getMail() wont work 

    getMail(); 
} 

var mail = new obj(); 
mail.getMail(); 
관련 문제