0

I'm trying to make private functions in Javascript. Here is my code:

function Person() {
  this.id = 5;
};

Person.prototype = {
  getId: function() {
    return this.id;
  },
  walk: function() {
    alert("i am private");
  },
  eat: function() {
    alert("i am public");
  }
};

I want to make walk function private one and eat function is public .

Doug
  • 3,312
  • 1
  • 24
  • 31
dina saber
  • 103
  • 2
  • 12
  • What are your definitions of `private` and `public` ? – Rayon Mar 10 '16 at 11:29
  • private one cant be accessed outside class even by making object while we can access public one – dina saber Mar 10 '16 at 11:31
  • Possible duplicate of [How do I mimic access modifiers in JavaScript with the Prototype library?](http://stackoverflow.com/questions/1958216/how-do-i-mimic-access-modifiers-in-javascript-with-the-prototype-library) – Bonatti Mar 10 '16 at 12:01

1 Answers1

1

There is no constructions in JavaScript to define real private methods for class, but you can do so:

var Person = (function () {
    var Person = function () {
        this.id = 5;
    };

    var walk = function () {
        alert("i am private");
    };

    Person.prototype = {
        constructor: Person,
        getId: function (){
            return this.id;
        },
        eat: function () {
            alert("i am public");
        }
    };

    return Person;
}());
Dmitriy
  • 3,745
  • 16
  • 24