从对象函数中获取函数

时间:2016-11-06 00:36:33

标签: 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().toggle('hide');

3 个答案:

答案 0 :(得分: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 ) 希望这有帮助。

答案 1 :(得分: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的最佳实现:/

答案 2 :(得分: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');