2011-10-28 4 views
2

좋아요, OOP를 처음 접하시는 분들도 괜찮을 것 같습니다.jS OOP 중첩 함수

메신저 JS 개체 라이브러리의 무언가를 만들려고 시도하고 중첩 된 함수를 사용하여 할 수 있을지 궁금해하고 있었습니까 ??

var object = new function() { 

    this.action1 = function() { 
     this.dostuff1 = function() { 
      return "dostuff1"; 
     }; 

    this.dostuff2 = function() { 
      return "dostuff2"; 
    };     
}; 

세 번째 레벨 기능에 액세스하는 데 문제가 있습니다. 이렇게 둥지를? 수 있습니까?

this.action2 = function() { 
    return "action2"; 
}; 

alert(object.action1.dostuff2()); 
+1

당신은 확실히 중첩 된 함수를 만들 수 있지만, 당신은 아마 발생하는 문제는'this' 키워드의 사용과 관련이있다. JavaScript에서 어떻게 작동하는지 (https://developer.mozilla.org/en/JavaScript/Reference/Operators/this)를 읽었습니까? Java와 같은 클래스 기반 OO 언어에서 일어나는 것과는 조금 다릅니다. – nnnnnn

+0

'this.action1'을 닫는'};가 없습니다. – oesgalha

답변

2

는 일부 코드 정리 내용은 아래를 참조하십시오 :이 도움이

var o = (new function() {   // changed 'object' to 'o' 
    this.action1 = (function() {  // added parentheses, not required. 
    this.dostuff1 = (function() { // does not return anything. 
     return "dostuff1";   // and is also not the proper way to organize 
    });        // ** look at the javascript prototype 
    return this;     // now it does 
    });        // missing closing bracket 

    this.dostuff2 = (function() { 
    return "dostuff2"; 
    });     
}); 

alert(o.action1().dostuff2());  // action1 is a function, not a variable. 

희망을. 또한 여기에 brief tutorial on the javascript prototype이 있습니다.

3

Eberlin의 대답은 완벽하게 정확하지만 중첩 된 개체를 만들어 차례대로 함수 자체를 중첩하는 대신 함수를 다시 노출하는 것이 좋습니다. 그렇지 않으면 유지 보수의 악몽이 될 수 있습니다.

기본적으로 당신이

var Child = function(){ 
    //constructor 
}; 

Child.prototype.doStuff2 = function(){ 
    return "dostuff2"; 
}; 

var Root = function(obj){ 
    //constructor 
    this.child = obj; 
}; 

Root.prototype.action1 = function(){ 
    return "doStuff1"; 
}; 

//usage 
var myRoot = new Root(new Child()); 
myRoot.action1(); 
myRoot.child.action2(); 

를 만들 수 있습니다 여기에 라이브 예제 : http://jsbin.com/ijotup/edit#javascript,live