JavaScript Event implementation to Closure based Object

牧云@^-^@ 提交于 2019-12-02 10:08:25

In your first block of code, you are returning an object, which is different from this or self.

You don't necessarily have to return this in your constructors but you should assign your functions on the returned object. If you create a variable for the object you want to return, you can use it in your setTimeout callback like so:

var class1 = function(val1)
{
    var val = val1;    

    var obj = {
        f1: function()
        {
            return val;
        },
        onEvent: function()
        {
            console.log('not implemented yet. Override');
        }
    };

    setTimeout(function()
    {
        obj.onEvent();

    }, 1000);

    return obj;
};

For extra style points, you might want to capitalize the name of your constructors (and perhaps use new to instantiate them to make things clearer to your readers).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!