我的代码就是这个:
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"));
});
答案 0 :(得分:2)
当一个函数被调用作为click事件的回调时,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 :(得分: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