最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I add a prototype function to an event listener in the initialization function? - Stack Overflow

programmeradmin0浏览0评论

I'm not sure exactly how to phrase my question, so let me present an example:

function foo() {
  window.addEventListener("keydown", function(event) {
        bar(event.keycode);
}

foo.prototype.bar = function (keycode) {
//code
}

I've tried using this.bar(), but that results in using the window as this. Is there a way to do this, or will I have to call another initialize method manually?

I'm not sure exactly how to phrase my question, so let me present an example:

function foo() {
  window.addEventListener("keydown", function(event) {
        bar(event.keycode);
}

foo.prototype.bar = function (keycode) {
//code
}

I've tried using this.bar(), but that results in using the window as this. Is there a way to do this, or will I have to call another initialize method manually?

Share Improve this question edited Jul 6, 2012 at 14:49 Esailija 140k23 gold badges279 silver badges328 bronze badges asked Jul 6, 2012 at 14:27 BloodyaugustBloodyaugust 2,5038 gold badges31 silver badges46 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 8

Bind this.bar to this before you pass it.

function foo() {
    window.addEventListener("keydown", this.bar.bind(this), false);
}


foo.prototype.bar = function (event) {
    console.log(event.keyCode);
}

demo http://jsfiddle.net/2tee4/

An alternative solution if you don't have Function.prototype.bind available*, and you're unwilling to add extra functions to Function.prototype would be to close over the call to this.bar:

function foo() {
    var self;
    self = this;
    window.addEventListener('keydown', function (e) {
        self.bar(e);
    }, false);
}
foo.prototype.bar = function (e) {
    console.log(e.keyCode);
}

* although your use of addEventListener without attachEvent leads me to believe that Function.prototype.bind would be an acceptable choice


Additionally, libraries such as jQuery may include their own form of bind, jQuery's is jQuery.proxy.

If your intention is to add a new listener for every foo created, another option is to make foo implement the EventListener interface, and simply pass this in place of the handler.

function Foo() {
    window.addEventListener("keydown", this, false);
}

Foo.prototype.bar = "foobar";

Foo.prototype.handleEvent = function(e) {
    console.log(e.type);   // "mousedown" (for example)
    console.log(this.bar); // "foobar"
};

new Foo();

Note that this only works with addEventListener().

DEMO: http://jsfiddle.net/k93Pr/

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论