Javascript 从对象函数中获取函数

Javascript 从对象函数中获取函数,javascript,oop,Javascript,Oop,我一直在学习OOP和JavaScript,想知道如何让这样的东西工作起来 function myApp(){ this.nav = function(){ function toggle(state = 'show'){ //toggle nav code... } toggle(); } } var app = new myApp(); app.nav(); 如何从这里像这样访问切换函数 app.nav().togg

我一直在学习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');

您应该返回对象以使方法可链接。
你的定义可以是:

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的最佳实现:/

您应该返回对象以使方法可链接。
你的定义可以是:

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的最佳实现://

您需要返回this
这里有一个例子:

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)。

希望得到帮助。

您需要返回此文件
这里有一个例子:

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)。

希望这有帮助。

我更喜欢这样:

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');

我更喜欢这样:

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');

你的函数必须
返回{toggle:function(){…}}
才能链接你的函数必须
返回{toggle:function(){…}}
才能链接谢谢,我在玩这个我遇到了这个场景,很好奇谢谢,我在玩这个我遇到了这个场景,很好奇