简体   繁体   中英

Private functions in namespaced javascript

I'm trying to define a way in which I can control the access to methods for the javascript we use at work (Part of a coding standards improvement drive).

The pattern I was planning to use was fine until I thought about what we do with 3rd party script methods.

How can I tweak my code to allow access to the private function from inside the jQuery method?

var NameSpace = new function () {

    // My private function I want to access.
    var privateFunction = function () {

    };

    this.publicFunction = function () {

        // I can access my private function here.
        privateFunction();

        jQuery(window).resize(function () {

            // But not here :(
            privateFunction();

        });
    };
};
    // I can access my private function here.
    privateFunction();
    jQuery(window).resize(function () {
        // But not here :(
        privateFunction();
    });

Yes you can. JavaScript is statically scoped. You can access all the variables and functions of each enclosing scope in that resize callback, including privateFunction (as long as you haven't shadowed it by defining a privateFunction in a nested scope).

What you can't do is access any of those local variables outside the enclosing function.

I'm trying to define a way in which I can control the access to methods for the javascript we use at work (Part of a coding standards improvement drive).

I would suggest that this is a pointless exercise.

Namespacing is good for avoiding unwanted name clashes. What truly 'private' members are for is strictly enforcing rigid security boundaries. But this is JavaScript: you aren't running code with different access levels and sandboxing here, like you might in Java. You don't have to blindly reproduce the security model of Java in JavaScript. Who is the 'attacker' here? Yourself? Other coders in your team?

Data hiding and encapsulation is good practice, but you don't need to strictly enforce privateness to achieve this. Indeed, having real privates may make debugging and prototyping tasks more difficult. Consider the Python-like approach where you simply mark members that aren't supposed to be used from outside, for example with a leading underscore. Anyone using a pseudo-private member knows they're doing something they shouldn't, and hopefully have a good temporary reason for doing so.

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