绑定函数,包含" this" (JQuery的)

时间:2015-05-28 12:50:52

标签: javascript jquery

考虑以下对象:

var obj = {
  name: "pete",
  funct : function () { console.log("I am", this); }
}

将obj.funct绑定到事件处理程序时,会丢失对该对象的引用,它现在引用全局对象(窗口)。

所以,这不能正常工作:

$(window).bind("keypress", obj.funct);

如果this在事件处理程序调用时仍然指向我的对象,我怎么能保证?

2 个答案:

答案 0 :(得分:1)

制作一个参考范围的范围变量。

select 
f.*, 
case  
  when r.format is not null then 'Can\'t remove' else 'Remove this' end 
as message 
from rp_format f 
left join rp_records r on r.format = f.fid 
group by f.fid  ;


+------+--------------+--------------+
| fid  | recordformat | message      |
+------+--------------+--------------+
|    1 | CD           | Can't remove |
|    2 | Vinyl        | Can't remove |
|    3 | DVD          | Can't remove |
|    4 | Test         | Remove this  |
+------+--------------+--------------+

或者你可以采取另一种方法

var that = this;
var obj = {
  name: "pete",
  funct : function () { console.log("I am", that); }
}
var HoldAllValues = function(){
  var origin = this;
  this.name = "pete",
  this.funct = function () { console.log("I am", origin.name);origin.name = 'amnesia'; }
}
var gatekeeper = new HoldAllValues();
$(window).bind("keypress", gatekeeper.funct);

答案 1 :(得分:0)

使用bind并传递此信息:

var obj = {
  name: "pete",
  funct : function () { console.log("I am", this); }.bind(this)
}