2014-02-26 56 views
1

早上好,我正在从JavaScript的函数式编程方法转向面向对象的方法学,并且有一个问题。在函数式编程我可以调用一个函数另一个函数内。例如:JavaScript OOP参考方法

function a(){ 
    // do something and when done call function b 
    b(); 
} 

function b(){ 
    // does more stuff 
} 

现在,我切换到OOP的做法我将如何调用对象的方法从同一个对象的另一种方法。例如:

var myClass = function(){ 
    this.getData = function(){ 
     //do a jquery load and on success call the next method 
     $('#a').load('file.asp',function(response,status,xhr){ 
      switch(status){ 
       case "success": 
        //THIS IS WHERE THE QUESTION LIES 
        this.otherfuntcion(); 
       break; 
      } 
     } 
    } 

    this.otherfunction = new function(){ 
     // does more stuff 
    } 
} 

p = new myClass(); 
p.getData(); 

我可以说this.b()成功调用方法b还是必须做别的事情?先谢谢你。

+0

拼写错误。 'this.otherfunction()' –

+0

就像一个资源可以帮助你一样.. http://stackoverflow.com/a/13074081/1257652 –

回答

5

这将是更非常缓慢方法和很多实例。改用原型:

var myClass = function(){ 

} 
myClass.prototype = { 
    getData: function(){ 
     //do a jquery load and on success call the next method 
     $('#a').load('file.asp',function(response,status,xhr){ 
      switch(status){ 
       case "success": 
        //THIS IS WHERE THE QUESTION LIES 
        this.otherfunction(); 
       break; 
      } 
     }.bind(this)) 
    }, 
    otherfunction: new function(){ 
     // does more stuff 
    } 
}; 


p = new myClass(); 
p.getData(); 
+0

不是'this'里面的完全回调是指jqXHR对象吗? –

+0

不,绑定'改变了回调的范围... – inf3rno

+0

对不起,没有看到它 –

1

您的匿名回调函数中的this上下文与您的类的方法内部的上下文不同。因此,你需要一个参考存到自己的上下文闭包内:

var that = this; 
$('#a').load('file.asp',function(response,status,xhr){ 
    switch(status){ 
     case "success": 
      //THIS IS WHERE THE QUESTION LIES 
      that.otherfuntcion(); 
     break; 
    } 
}); 

的替代将是一个特定的上下文绑定到你的匿名函数:

$('#a').load('file.asp',function(response,status,xhr){ 
    switch(status){ 
     case "success": 
      //THIS IS WHERE THE QUESTION LIES 
      this.otherfuntcion(); 
     break; 
    } 
}.bind(this)); 
+0

我们通常在这种情况下调用一个'bind'来改变作用域,使用'''','自我'等等,不推荐很长时间。 – inf3rno

0

您应该将外部函数上下文复制到新变量中,以直接引用外部上下文。 this在内部功能是这个内部功能的上下文。

var self = this; 
$('#a').load('file.asp',function(response,status,xhr){ 
    switch(status){ 
     case "success": 
      //THIS IS WHERE THE QUESTION LIES 
      self.otherfuntcion(); 
     break; 
    } 
}