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 .

3
  • What are your definitions of private and public ? Commented Mar 10, 2016 at 11:29
  • private one cant be accessed outside class even by making object while we can access public one Commented Mar 10, 2016 at 11:31
  • Possible duplicate of How do I mimic access modifiers in JavaScript with the Prototype library? Commented Mar 10, 2016 at 12:01

1 Answer 1

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;
}());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.