0

オブジェクトをクリックした後、一部のデータを処理するために使用するオブジェクトがすべての値を失います。クロージャーが原因であることはわかっていますが、修正方法がわかりません。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){
        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"));
}); 
4

2 に答える 2

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;             
 } 
于 2013-03-19T18:24:03.707 に答える
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;             
 }        

それが役立つことを願っています。

スジ

于 2013-03-19T19:47:22.213 に答える