function createPerson() {
const privateData = {
name: '',
age: 0
};
return {
setName(name) {
privateData.name = name;
},
setAge(age) {
privateData.age = age;
},
getInfo() {
return `Name: ${privateData.name}, Age: ${privateData.age}`;
}
};
};
//or
const person = createPerson();
person.setName('John');
person.setAge(30);
console.log(person.getInfo()); // logs "Name: John, Age: 30"
console.log(person.privateData); // logs undefined
Here privateData is private property is not accesible from outside.
Here approach is to use a factory function to create instances of an
object with private properties.
No comments:
Post a Comment