在FreeCodeCamp构建安全可靠的人员对象
本文提供一种在FreeCodeCamp中创建更安全、更灵活的人员对象的方法,解决原代码中first
和last
属性未正确存储的问题。 我们将使用私有变量和getter/setter方法来实现更好的数据封装和完整性。
改进后的代码如下:
const Person = function(first, last) {
let _first = first;
let _last = last;
this.getFirstName = function() {
return _first;
};
this.getLastName = function() {
return _last;
};
this.getFullName = function() {
return _first + ' ' + _last;
};
this.setFirstName = function(first) {
_first = first;
};
this.setLastName = function(last) {
_last = last;
};
// `setFullName` 方法不再需要
};
通过getter方法(getFirstName
, getLastName
, getFullName
)访问姓名信息,通过setter方法(setFirstName
, setLastName
)修改姓名信息。 这确保了对内部数据的安全访问和修改。
使用方法示例:
const person = new Person('John', 'Doe');
console.log(person.getFirstName()); // 'John'
console.log(person.getLastName()); // 'Doe'
person.setFirstName('Jane');
console.log(person.getLastName()); // 'Doe'
这种方法有效地避免了直接访问和修改内部变量,提高了代码的安全性,并增强了对象的封装性。