Marcin K
Marcin K

Reputation: 751

How to use a private members from static methods in JavaScript?

I would like to use a private (static) method from a public static method in JavaScript. I was looking into this solution:

function Calc() {
    var DoSmth = function (test) {
        return test + 1;
    }
}

Calc.Stat = function (x) {
    return DoSmth(x);
}

But it wont work. How do I do such a thing?

Upvotes: 0

Views: 86

Answers (3)

Magus
Magus

Reputation: 15104

var Calc = (function() {
    var DoSmth = function (test) {
        return test + 1;
    };

    var klass = function() {

    };

    klass.Stat = function (x) {
        return DoSmth(x);
    };

    return klass;
})();

Upvotes: 2

elclanrs
elclanrs

Reputation: 94101

You can do this using a module pattern:

var Calc = (function() {
  var run = function() { ... },
      stat = function() { return run(); };
  return { stat: stat };
}());

Calc.stat();

Upvotes: 0

Krzysztof
Krzysztof

Reputation: 16130

The easiest way to do private function in JS is to wrap it with another function. I suggest something like this:

var Calc = (function() {
    var DoSmth = function (test) {
        return test + 1;
    };

    var result = function() {

    };

    result.Stat = function (x) {
        return DoSmth(x);
    }

    return result;
}());

Upvotes: 0

Related Questions