开发者

Cannot access object's methods from within event handler using `this`

开发者 https://www.devze.com 2023-01-11 01:11 出处:网络
Below is my code for FF Extension monitoring browsing behaviour. I can\'t access trim method from processClick method handling click event.

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)
开发者_StackOverflow中文版{
    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);
};
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号