2016-11-06 50 views
0

我一直在學習OOP和JavaScript中玩耍,並想知道如何得到的東西看起來像這樣的工作中......獲取功能,從目標函數

function myApp(){ 

    this.nav = function(){ 

     function toggle(state = 'show'){ 
      //toggle nav code... 
     } 

    toggle(); 
    } 


} 

var app = new myApp(); 
app.nav(); 

怎麼會去訪問切換功能從這裏像這樣...

app.nav().toggle('hide'); 
+0

你的函數必須返回'{切換:函數(){...}}'是可鏈接 – adeneo

回答

2

您需要返回這個
這裏一個例子:

function myApp(){ 
    this.nav = function(){ 
    this.toggle = function(state = 'show'){ 
     console.log(state);  
    } 
    this.toggle(); 
    return this; 
    } 
} 

const app = new myApp(); 
app.nav(); // show 
app.nav().toggle('hide'); // show hide 

還需要將功能附加到對象(this.toggle)。
希望得到這個幫助。

+0

感謝,我用這個玩弄我來了在這種情況下,很好奇 – MykolaSenechyn

1

你應該返回的對象,使方法可鏈接。
你的定義是這樣的:

function myApp(){ 
    var self= this; 

    self.toggle = function(state = 'show'){ 
     //toggle nav code... 
     //return self? to make it chainable too 
    } 

    self.nav = function(){ 
    self.toggle(); 
    return self; 
    } 
} 

var app = new myApp(); 
app.nav(); 

,但是這不是OOP最佳執行:/

0

我更喜歡這樣的:

function myApp(){ 

    this.nav = function(){ 
     var core = { 
      toggle: toggle 
     } 
     function toggle(state = 'show'){ 
      if(state === "show") 
      { 
      console.log("showing state"); 
      } else { 
      console.log(state); 
      }   
     } 
     return core; 
    } 
} 

var app = new myApp(); 
app.nav().toggle(); 
app.nav().toggle('close');