"Friend classes" in javascript

I have a Factory class that creates a Widget object. The Factory object must call the Widget object's "private method" callback later to pass some ajax information to it. So far, the only implementation I came up with is to create a public method in the Widget that returns a private method in the factory and then removes itself, Factory then returns a new widget, keeping the 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 that I am experiencing, or is this a pretty reasonable approach? I know this works, just curious if I enter into any pitfalls that I should know about.

+3
2
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];
}

Tuple<Widget, function>

widgetCallback Widget

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;
        }
    }
}
+1

- JavaScript ( - GWT), ( , ... )

, .

, JavaScript, Ruby .., , ( Java + GWT , -), , , . "_" ( , ), . JavaScript , , .

; , , , ? ( ) , ?

0

Source: https://habr.com/ru/post/1684324/


All Articles