Member-only story
In JavaScript, objects are used to encapsulate data and behavior. While all object properties and methods are technically public by default, there are ways to achieve privacy and control access to these members.
In this article, we’ll explore the concepts of public and private members in JavaScript and how to implement them effectively.
Public Members
Public members are properties and methods that are accessible from outside the object. They can be read, modified, or invoked by any part of the code that has a reference to the object. By default, all properties and methods defined within an object are public.
Here’s an example of an object with public members:
const person = {
name: 'Alice', // Public property
age: 25, // Public property
greet: function() { // Public method
console.log(`Hello, my name is ${this.name}`);
}
};
console.log(person.name); // Output: Alice
person.age = 26; // Modifying a public property
person.greet(); // Output: Hello, my name is Alice
In this example, name
, age
, and greet
are all public members that can be…