Javascript 如何访问jQuery事件函数中的对象属性

Javascript 如何访问jQuery事件函数中的对象属性,javascript,jquery,Javascript,Jquery,对不起我的英语。下面是示例代码: /** * @constructor */ function MyNewClass(){ this.$my_new_button = $('<button>Button</button>'); this.my_value = 5; this.init = function (){ $('body').append(this.$my_new_button); this.$my_new_button.clic

对不起我的英语。下面是示例代码:

/**
 * @constructor
 */
function MyNewClass(){
  this.$my_new_button = $('<button>Button</button>');
  this.my_value = 5;

  this.init = function (){
    $('body').append(this.$my_new_button);
    this.$my_new_button.click(
      function (){
        // Its always alerts "undefined"
        alert(this.my_value);
      }
    )
  }
}
/**
*@constructor
*/
函数MyNewClass(){
这个。$my_new_button=$('button');
这个.my_值=5;
this.init=函数(){
$('body').append(这个.$my\u new\u按钮);
这是。$my_new_按钮。单击(
函数(){
//它总是提醒“未定义”
警报(此.my_值);
}
)
}
}
如何访问jQuery click事件函数中的对象
my_value
属性?
有可能吗?

您可以执行以下操作

function MyNewClass(){
    this.$my_new_button = $('<button>Button</button>');
    this.my_value = 5;
    var self = this; //add in a reference to this
    this.init = function (){
        $('body').append(this.$my_new_button);
        this.$my_new_button.click(
            function (){
                //This will now alert 5.
                alert(self.my_value);
            }
        );
    };
}
函数MyNewClass(){
这个。$my_new_button=$('button');
这个.my_值=5;
var self=this;//添加对此的引用
this.init=函数(){
$('body').append(这个.$my\u new\u按钮);
这是。$my_new_按钮。单击(
函数(){
//现在将向5发出警报。
警报(自我。我的_值);
}
);
};
}

这是javascript中的一个小模式(尽管我不知道这个名字)。它允许您访问内部函数中函数的顶级成员。在嵌套函数中,您不能使用“this”来引用顶级成员,因为它只引用您所在的函数。因此,需要将顶级函数“this”值声明为它自己的变量(在本例中称为self)。

Jquery有一个方法:

函数MyNewClass(){
这个。$my_new_button=$('button');
这个.my_值=5;
this.init=函数(){
$('body').append(这个.$my\u new\u按钮);
这是。$my_new_按钮。单击(
$.proxy(函数(){
//它总是提醒“未定义”
警报(此.my_值);
},本页)
)
}
}

function MyNewClass(){ 
  this.$my_new_button = $('<button>Button</button>');
  this.my_value = 5;

  this.init = function (){
    $('body').append(this.$my_new_button);
    this.$my_new_button.click(
      $.proxy(function (){
        // Its always alerts "undefined"
        alert(this.my_value);
      },this)
    )
  }
}