Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS: OOP private functions / private fields [duplicate]

Systemname =
{

Question :
{
    send: function()
    {
        console.log("send");
    },

    read:   function()
    {
        console.log("read");
    },

    delete: function()
    {
        console.log("delete");
    }
},

Answer :
{
    send: function()
    {
        console.log("Answer sent");
    }
},

Person :
{
    foo: 'foo',
    bar: 'bar',


    add: function(name)
    {
        console.log('person "' + name + '" added');
    },

    remove: function(id)
    {
        console.log('person with id "' + id + '" removed');
    }
}

}

i'm learning how oop works in js and i'm a bit confused now about private methods and fields. i'd like to have some private member in the person section such as 'personCount' or 'lastAddedPerson'. if i add them like this:

Person:
{
    personCount: 0,
    lastAddedPerson: '',
    ...
}

at the beginning of the person section, the fields are public and can be called with Systemane.Person.Field.... how can i set them private? and the same for a method.

thx for your help.

like image 648
roman Avatar asked Feb 16 '26 00:02

roman


1 Answers

Here is one way.

function Person(n) {
   var name = n;
   this.getName = function() {
     return name;
   }
   this.setName = function(newName) {
      name = newName;
   }
}

var person = new Person('roman');
like image 184
Justin Thomas Avatar answered Feb 18 '26 19:02

Justin Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!