2013-03-19 51 views
0

点击一个对象后,我用来处理一些数据的对象失去了所有的值,我知道这是因为关闭,但我不知道如何解决它,这是第一个我在Js与OOP一起工作。OOP Jquery丢失值因为关闭

我的代码是这一个:

function control_hermes(){ 
    this.url_base="http://domain.com"; 
    this.action=""; 
    this.set_id_to_update; 
    //private 
    function set_action(parameter_to_control){ 
     this.action=parameter_to_control; 
    } 
    //private 
    function get_full_url(){ 
      console.log(this.action); //undefined?????, should be the id of the button 
      console.log(this.url_base); //undefined?????, is on the top!!! 
      return this.url_base+"?"+this.action;    
    }    
    //public 
     this.execute_instruction=function(id_button){ 
      set_action(id_button); 
      var url=get_full_url(); 
    } 
}//end class  


//use class 
var manager_hermes=new control_hermes(); 
jQuery('input').click(function(){ 
    manager_hermes.execute_instruction(jQuery(this).attr("id")); 
}); 

回答

2

当一个函数被调用的点击事件的回调,this将引用该事件被绑定到的元素。为了解决这个问题,请将外部引用this存储在另一个变量中。这通常使用名为self的变量来完成。

var self = this; 
this.url_base="http://domain.com"; 
this.action=""; 
this.set_id_to_update; 
//private 
function set_action(parameter_to_control){ 
    this.action=parameter_to_control; 
} 
//private 
function get_full_url(){ 
     console.log(self.action); //undefined?????, should be the id of the button 
     console.log(self.url_base); //undefined?????, is on the top!!! 
     return self.url_base+"?"+self.action;    
} 
1

http://jsfiddle.net/sujesharukil/25bcG/1/

创建一个小提琴。新增

var self = this; 

位于班级顶部。然后引用它。

function set_action(parameter_to_control){ 
    self.action=parameter_to_control; 
} 

//private 
function get_full_url(){ 
     console.log(self.action); //undefined?????, should be the id of the button 
     console.log(self.url_base); //undefined?????, is on the top!!! 
     return this.url_base+"?"+this.action;    
}   

希望有帮助。

Suj