我在这里阅读了一些文章和问题,但我仍然不明白如何实现这一目标。以下代码片段将帮助我解释我想要做什么:
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;
}
我继续创建了几个实例:
var emp1 = new Employee(1,'Brendan Eich','brendaneich@gmail.com');
当我使用var
时对于像 id
这样的变量& name
它们的行为就像私有(private)成员,但我无法从 getId()
等方法访问它们和getName()
定义于 Employee.prototype
.
另一方面声明 email
与 this._email = email
一切正常,但这并不能保护隐私,因为我可以直接将其作为对象属性访问,而不需要访问方法。
我想知道的是:
- 使用构造函数时声明私有(private)变量的最佳方式是什么?
- 如果我使用
var
声明变量那么它会驻留在对象的哪里?
最佳答案
试试这个:
function Employee(id, name, email){
var _id = id; //private
var _name = name; //private
this._email = email; //public
var fooPrivate = function(){
return ;
}
this.getId = function(){ //Public function
fooPrivate(); //I can only be called inside other member functions
return _id;
}
this.getName = function(){ //Public function
//Note that you don't use this._name for private variables
return _name;
}
this.getEmail = function(){ //Public function
return this._email;
}
}
使用构造函数时声明私有(private)变量的最佳方式是什么?
如果我使用 var 声明变量,那么它将驻留在对象中的什么位置?
function Employee{ //private only accessible here... }
关于javascript - 在 ES5 中使用私有(private)成员变量和构造函数的最佳实践是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44297545/