我的问题是,当我尝试为某个对象添加函数作为监听器时,它不遵守 this
创建正在调用的函数的范围。
现场演示:http://jsfiddle.net/Ht4x9/
如你所见showAct()
将打印“MyActivity”,但是单击红色 <div>
将不会。
结果是:
MyActivity
undefined
我怎样才能点击<div>
也打印出来?将对象作为函数的参数传递真的有必要吗?我想以尽可能干净的方式进行。
下面粘贴代码以防万一
谢谢!
JS
var activity = 'MyActivity';
var Screen = {
act: activity,
_privFunc: function()
{
console.log(this.act);
},
publicFunc: function()
{
$('div').on('click', this._privFunc);
},
showAct: function()
{
this._privFunc();
}
}
Screen.publicFunc();
Screen.showAct();
HTML + CSS
<div>CLICK</div>
div { background: red; width: 100px; height: 100px; cursor: pointer; font-weight: bold
最佳答案
当事件处理程序默认执行时,处理程序内部的 this
将引用处理程序注册到的 dom 元素。在您的情况下,您需要使用自定义执行上下文来执行回调函数。这可以通过使用 $.proxy() 来完成
jQuery: $.proxy()
$('div').on('click', $.proxy(this._privFunc, this));
下划线:bind()
$('div').on('click', _.bind(this._privFunc, this));
现代浏览器:bind()
$('div').on('click', this._privFunc.bind(this));
关于javascript - 使用监听器时无法传递 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19625658/