Javascript OOP Jquery由于闭包而丢失值
在点击一个对象后,我用来处理一些数据的对象失去了所有的值,我知道这是因为闭包,但我不知道如何修复它,这是我第一次在Js中使用OOP 我的代码是:Javascript OOP Jquery由于闭包而丢失值,javascript,jquery,oop,Javascript,Jquery,Oop,在点击一个对象后,我用来处理一些数据的对象失去了所有的值,我知道这是因为闭包,但我不知道如何修复它,这是我第一次在Js中使用OOP 我的代码是: function control_hermes(){ this.url_base="http://domain.com"; this.action=""; this.set_id_to_update; //private function set_action(parameter_to_control){
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"));
});
当调用函数作为单击事件的回调时,
此
将引用事件绑定到的元素。要解决此问题,请将对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;
}
当调用函数作为单击事件的回调时,
此
将引用事件绑定到的元素。要解决此问题,请将对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;
}
创造了一把小提琴。增加
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
创造了一把小提琴。增加
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;
}
希望有帮助
苏吉