简体   繁体   中英

How to call function A from function B within the same namespace?

Let's say I have the namespace,

var Namespace = {
    A : function() {
        alert('Hello!');
    },
    B : function() {
        // Call A() from here, do other stuff
    }
}

In this namespace, I intend for A to be a helper function to B. That is to say, A() will never be called outside the namespace. It will only be called by the functions within the namespace.

What's the best way to address the issue of a local/helper function within a namespace? The way I see it there are two possibilities:

// Method #1    
var Namespace = {
    A: function() {
        alert('Method #1');   
    },

    B : function() {
        Namespace.A();
    }
}

Namespace.B();

// Method #2
function Namespace2() {
    var A = function() {
        alert('Method #2');
    };

    this.B = function() {
        A();        
    }
}

var ns2 = new Namespace2();
ns2.B();

In the first method, it is ugly and awkard to type Namespace.A() (repeatedly) in every function within the namespace. This leads me to prefer Method #2. But I was curious what was the best practice here.

I recommend placing the "namespace" inside a function scope. Everything not explicitly public will be naturally private:

var Namespace = (function() {
    var self = {};

    // Private
    var A = function() {
        ...
    };

    // Public
    self.B = function() {
        A();
    }

    return self;
}());

Namespace.B(); // Works
Namespace.A(); // Doesn't work

您可以使用this语句调用它

this.A();

Well you can event use a third option where the Namespace is created in it's own scope:

var Namespace = (function(){
    var A = function() {
        alert('scoped method');
    };

    function Namespace() {

          var A1 = function() {
               alert('Namespace "private" method');
          };

          Namespace.prototype.B1 = function(){
              A();  //will run
              A1(); //will run with no errors
          };

    };

    Namespace.prototype.B = function(){
        A();  //will run
        A1(); //ERROR!
    };

    return Namespace;
})();

If you only intend to use A inside B , why not define it inside B ?

var Namespace = {
    B: function() {
        var A = function() {
            ...
        }

        A();
    }
};

Namespace.B();
var Namespace = {
    A : function() {
        alert('Hello!');
    },
    B : function() {
        Namespace.A();
    }, 
}

note the Semi-colon at the end

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