开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜