开发者

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.


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


this.before = function(){return "public"};
this.publicFucntion = function(){privateFunction(this.before());}

Then just override this.before.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜