Search code examples
javascriptpublic-method

Why are these methods public?


My javascript looks like the following. I don't understand why these methods are all public though?

Something.RegisterNamespace("One.ABC");

    (function(ABC) {

      ABC.SayHello = function() {
             alert('hello');

      };

    })(One.ABC);

So now I can do:

One.ABC.SayHello();

Solution

  • You are adding the SayHello function into the object being passed in, which is One.ABC. What else are you expecting? If you want a private function, define it inside your anonymous function (var SayHello = function(){...}) without adding it to the object. Not sure what you're trying to accomplish...

    EDIT:

    Here's how I would rewrite your code to do what I think you want:

    One = {};
    One.ABC = {};
    
    (function(ABC) {
        var PrivateHello = function(){
            alert('hello');
        };
        ABC.PublicHello = function() {
            PrivateHello();
        };
    })(One.ABC);
    
    One.ABC.PublicHello(); // alerts 'hello'
    One.ABC.PrivateHello(); // error 'One.ABC.PrivateHello is not a function'