简体   繁体   中英

Revealing class pattern vs prototype method?

I've seen the revealing module pattern, as well as the prototype class pattern. I kind of adapted the two together into a revealing class pattern. I'm trying to figure out if there are any gotchas with this pattern, or things that wouldn't work. As long as the constructor for the object is typeof "function" I would think there wouldn't be any problems.

The only caveat I can come up with, is a high volume instantiated class, where the private functions are getting create every time a new class is created. This may cause memory problems for thousands of instantiations. For larger classes that don't build up in memory, though, my thinking is the easier code readability and security may be of benefit. By keeping functions private and revealing them, the obfuscator minimizes all of the internal functions, making it difficult for prying eyes. Granted, it is not foolproof, but just an extra layer of protection. Additionally, being able to work inside of the function privately, removes hundreds of occurrences of "this" within the class. Maybe it's a small advantage, but for complex code it kind of improves the readability. Anybody see any major problems with the pattern?

//standard pattern

var MyClass = function() {
    this.func1 = function() {
        //dostuff
    };
};
MyClass.prototype.func2 = function() {
    this.func1();
    //dostuff
};

-

//revealing class pattern

var MyClass = function() {
    function privateFunc() {
        //dostuff
    }

    function publicFunc() {
        privateFunc();
        //dostuff
    }

    this.publicFunc = publicFunc;
};

I've seen the revealing module pattern, as well as the prototype class pattern. I kind of adapted the two together into a revealing class pattern.

You should have a look at the revealing prototype pattern which truly combines them to reveal a class. What you currently have should rather be called "revealing instance pattern".

Anybody see any major problems with the pattern?

You've stated the major caveat already, but if you consider it worth then go for it. Given that most classes are not instantiated in very large volumes this doesn't really make a difference any more.

However, you could improve your pattern. Given that you don't use the prototype any more, there's no reason to keep it. Drop the new operator, drop using the this keyword in the constructor, and return an object literal. Voilá, you've got a factory function !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM