Search code examples
javascriptoopfriend-class

"Friend Classes" in javascript


I have a Factory class that creates a Widget object. The Factory object needs to callback a "private method" of the Widget object at a later time to pass it some ajax info. So far, the only implementation I've come up with is to create a public method in the Widget that returns the private method to the factory, and then deletes itself, the Factory then returns the new Widget while retaining a pointer to the private method. Here is a simplified example:

function Factory()
{
    var widgetCallback = null;

    this.ajaxOperation = function()
    {
        //some ajax calls
        widgetCallback('ajaxresults');
    }

    this.getNewWidget = function()
    {
        var wid = new Widget();
        widgetCallback = wid.getCallback();
        return wid;
    }

    function Widget()
    {
        var state = 'no state';
        var self = this;
        var modifyState = function(newState)
        {
            state = newState;
        }

        this.getState = function()
        {
            return state;
        }

        this.getCallback = function()
        {
            delete self.getCallback;
            return modifyState;
        }
    }
}

Is there a better way to achieve the effect I'm after or is this a fairly reasonable approach? I know it works, just curious if I'm stepping into any pitfalls I should be aware of.


Solution

  • this.getNewWidget = function() {
        var val = new Widget(),
            wid = val[0],
            widgetCallback = val[1];
    
        return wid;
    }
    
    function Widget() {
        var state = 'no state';
        var self = this;
        var modifyState = function(newState) {
            state = newState;
        }
    
        this.getState = function() {
            return state;
        }
    
        // Return tuple of Widget and callback
        return [this, modifyState];
    }
    

    Just get your constructor to return a Tuple<Widget, function>

    Alternative just use closure scope to edit widgetCallback directly in your Widget constructor

    function Factory() {
        var widgetCallback = null;
    
        this.ajaxOperation = function() {
            //some ajax calls
            widgetCallback('ajaxresults');
        }
    
        this.getNewWidget = function() {
            return new Widget();;
        }
    
        function Widget() {
            var state = 'no state';
            var self = this;
            // set it directly here!
            widgetCallback = function(newState) {
                state = newState;
            }
    
            this.getState = function() {
                return state;
            }
        }
    }