0

可能重复:
在 JavaScript 类中使用“this”的 setTimeout()</a>

我发现这篇关于如何使用原型在 javascript 中实现自定义事件的有趣文章:http ://www.nczonline.net/blog/2010/03/09/custom-events-in-javascript/

但我对如何实现这一点有点困惑,我有一个简单的应用程序,它的间隔每秒触发一个函数。

function App() {
    window.test = 'test';

    this.loginTimer = setInterval(this.checkLogin, 1000);

    EventTarget.call(this);
}
App.prototype = new EventTarget();
App.prototype.constructor = App;

App.prototype.checkLogin = function() {
    this.fire('test');
}

但这给我一个错误:

未捕获的类型错误:对象 [object Window] 没有方法“fire”

我使用了与文章中描述的相同的方法,有什么我遗漏的吗?

4

1 回答 1

0
var app;
function createApp() {
    if (app) return app; // singleton - always the same instance
    app = new EventTarget(); // basically being the EventTarget object
    // and extending it with additional properties (as following)
    // you also could make the EventTarget a property of a plain app object
    app.checkLogin = function() {
        this.fire('test'); // this === app if invoked as a method
    }
    app.loginTimer = setInterval(function() {
        app.checkLogin(); // call the method *on* the app
    }, 1000);
    return app;
}

var player;
function createPlayer() {
    if (player) return player; // again, singleton pattern
    player = {};
    player.play = function() {
        console.log('event tester');
    };
    // get the app singleton (or create it if not existing)
    // and add the listener to it
    createApp().addListener('test', function() {
        player.play(); // call the method
    });
}

// usage:
createApp();
createPlayer();
// starts logging "event tester"
于 2012-11-07T11:19:38.827 回答