无法使用`this`在事件处理程序中访问对象的方法 [英] Cannot access object's methods from within event handler using `this`

查看:140
本文介绍了无法使用`this`在事件处理程序中访问对象的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是FF Extension监控浏览行为的代码。
我无法从 processClick 方法处理点击事件访问 trim 方法。



控制台显示 this.trim 不是函数。
我知道这可能与这个范围有关。



我会很感激任何帮助

 函数bbm(doc)
{
this.doc = doc;

this.registerListeners = function(){
this.doc.addEventListener(click,this.processClick,false);
};

this.trim = function(str)
{
return str.replace(/ ^ \s + | \s + $ / g,'');
};


this.processClick = function(e){
alert(e.type ++ this.trim(this.url));
};

};


解决方案

使用此功能

  Function.prototype.bind = function(obj){
var _method = this;
return function(){
return _method.apply(obj,arguments);
};

$ / code>

然后,

  this.registerListeners = function(){
this.doc.addEventListener(click,this.processClick.bind(this),false);
};


Below is my code for FF Extension monitoring browsing behaviour. I can't access trim method from processClick method handling click event.

Console shows this.trim is not a function. I know that it maybe something with this scope.

I will be really grateful for any help.

function bbm(doc)
{
    this.doc = doc;

    this.registerListeners = function() {
        this.doc.addEventListener("click", this.processClick, false);
    };

    this.trim = function(str)
    {
        return str.replace(/^\s+|\s+$/g, '') ;
    };


    this.processClick = function(e) {
        alert(e.type + " " + this.trim(this.url));
    };

};

解决方案

Use this function

Function.prototype.bind = function(obj) {   
    var _method = this;
    return function() {
        return _method.apply(obj, arguments);
    };    
} 

Then,

this.registerListeners = function() {
     this.doc.addEventListener("click", this.processClick.bind(this), false);
};

这篇关于无法使用`this`在事件处理程序中访问对象的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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