绑定这个?变得不确定? [英] Binding this? Getting undefined?

查看:91
本文介绍了绑定这个?变得不确定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

p.test = 'hello';    

$('#btn').on('click', function(event){
    console.log(this.test); //undefined
}).bind(this);

我试图在一次单击中访问我的var,我正在使用bind,但它仍记录未定义".

I'm trying to access my var inside a click, Im using bind but it's still logging 'undefined'.

我要去哪里错了?

推荐答案

bind放置错误.您想将this绑定到事件处理函数,而不是绑定到从'on'方法返回的对象的jQuery集合.

The bind is placed wrong. You want to bind this to the event handler function, not to the jQuery collection of objects which are returned from the 'on' method.

以下示例应该可以工作:

Following sample should work:

$('#btn').on('click', function(event){
    console.log(this.test);
}.bind(this));

但是,这不是很好的做法.更好的方法可能是通过一些私有变量来引用this对象.常见的做法是将this对象缓存到一个称为self的局部变量中,该变量名为_this或..等.例如,您可以使用以下方法:

However, it's not very good practice. Better approach could be to reference the this object by some private variable. Common practice is to cache the this object into some local variable called self, that, _this or .. etc. For example you can use following approach:

var self = this;

$('#btn').on('click', function(event){
    console.log(self.test);
});

这篇关于绑定这个?变得不确定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆