JavaScript Event implementation to Closure based Object

后端 未结 1 1471
臣服心动
臣服心动 2021-01-26 12:42

I have a Object based on some closure, and want to implement event scheme here:

var class1 = function(val1)
{
    var val = val1;    
//------ want to call a met         


        
相关标签:
1条回答
  • 2021-01-26 12:57

    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).

    0 讨论(0)
提交回复
热议问题