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');
}
}
}
我正在学习 oop 如何在 js 中工作,现在我对私有(private)方法和字段有点困惑。我想在人员部分中有一些私有(private)成员,例如“personCount”或“lastAddedPerson”。如果我像这样添加它们:
Person:
{
personCount: 0,
lastAddedPerson: '',
...
}
在人员部分的开头,字段是公共(public)的,可以使用 Systemane.Person.Field 调用...我如何将它们设置为私有(private)?方法也是如此。
感谢您的帮助。
最佳答案
这是一种方法。
function Person(n) {
var name = n;
this.getName = function() {
return name;
}
this.setName = function(newName) {
name = newName;
}
}
var person = new Person('roman');
关于javascript - JS : OOP private functions/private fields,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15509811/