2011-10-28 63 views
2

好吧,這可能是一個noobolicious問題,即時消息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)?這與基於類的OO語言(如Java)發生的情況有點不同。 – 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