使用侦听器时无法传递“this”

Cannot pass "this" when using listener

本文关键字:this 侦听器      更新时间:2023-09-26

我的问题是,当我尝试将函数添加为某个对象的侦听器时,它不尊重创建正在调用的函数this范围。

现场演示:http://jsfiddle.net/Ht4x9/

如您所见showAct()将打印"我的活动",但是单击红色<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));

下划线:绑定()

$('div').on('click', _.bind(this._privFunc, this));

现代浏览器:绑定()

$('div').on('click', this._privFunc.bind(this));

您只需要使用bind并将第一个参数设置为this的预期目标。

正如Arun所建议的那样,如果你有jQuery并且你正在为旧版浏览器提供服务,$.proxy是一个不错的选择。

你为什么不使用类似于以下内容的东西?

var Screen = function () {
    var act = activity,
    _privFunc = function()
    {
        console.log(act);
    };
    this.publicFunc = function()
    {
        $('div').on('click', _privFunc);
    };
    this.showAct = function()
    {
        _privFunc();
    }
}
var s = new Screen();
s.publicFunc();
s.showAct();

http://jsfiddle.net/Ht4x9/7/