I am experimenting imitating OOP like behavior in JS. I am trying to have (private) variables: id
and name
in function Person
. To this function I am passing arguments which are used to initialize (private) variables. Then I am returning object having getter and setter for name
and only a getter for id
, thus effectively making id
read-only.
So id can be set only through constructor whereas name can be set and get anytime.
This is the code:
var Person = function (_id,_nm) {
var id, name;
this.id = _id;
this.name = _nm;
return {
setName: function (nm) {
name = nm;
},
getName: function () {
return name;
},
getId: function () {
return id;
},
print: function () {
document.writeln("Id: "+id+"<br />Name: "+name);
}
}
}
var person = new Person(123, "Mahesh");
person.print();
However when new Person(123,"Mahesh")
executes, I dont understand it is actually setting id
and name
or not, since while debugging I can see values set appropriately when hovered over them but Locals panel does not show them initialized:
Or either while in print() is is not referring to the desired id
and name
variables:
Whats wrong here?