Search code examples
javascriptclosuresprivate-members

Unable to access members in javascript


I'm defining a class in javascript as

    Class = (function() {
    var privateFunction = function() { return "private"; }
    return { publicFunction: function() { return privateFunction("public"); } };
    )();

Here user can access Class.publicFunction, but not Class.privateFunction.

Now I want to provide the user an interface to extend this Class. So I added a public function extend.

    Class = (function() {
            var privateFunction = function() { return "private"; }
            return { 
                    publicFunction: function() { return privateFunction("public"); } 
                    extend: function(source) { 
                            dest=this;
                            for(var prop in source)dest[prop] = source[prop]
                    }
            };
    )();

My aim was to use the extend attribute as follows

    Class.extend({
            someFunc: function() { return privateFunction("hooray"); }
    });

and access it as

    Class.someFunc()

The problem I face is the call to the privateFunction() in the extended function someFunc is not available for it. I can understand that it is the problem of the scope, but, is there anyway to solve my need.


Solution

  • While it's a horrible violation of encapsulation, you could do what you describe by passing the function you want to add as a string and evaling it in extend:

    Class.extend({
            someFunc: 'function() { return privateFunction("hooray"); }'
    });
    

    and in the extend function, change

                            for(var prop in source)dest[prop] = source[prop]
    

    to

                            for(var prop in source)dest[prop] = eval(source[prop])