I read a few articles and questions heres but I still don't understand how to achieve this. The following snippet will help me to explain what I am trying to do:
function Employee(id, name, email){
var _id = id;
var _name = name;
this._email = email;
}
Employee.prototype.getId = function(){
return _id;
}
Employee.prototype.getName = function(){
return this._name;
}
Employee.prototype.getEmail = function(){
return this._email;
}
I went on to create a couple of instances:
var emp1 = new Employee(1,'Brendan Eich','brendaneich@gmail.com');
When I am using var
for variables like id
& name
they behave like private members but I cannot access them from methods like getId()
and getName()
which are defined on Employee.prototype
.
On the other hand declaring email
with this._email = email
works all fine but this doesn't preserve privacy as i can access it asan object property directly without the need of an access method.
What i want to know:
- What is the best way to declare a private variable when using constructor functions?
- If i use
var
to declare variables then where will it reside in the object?