Encapsulation-tutorial
In the example below, we use Object.defineProperty to create private variables and expose them through getters and setters.
This way, the internal data can't be accessed or modified directly only through controlled methods.
Example:
Output
.webp)
This way, the internal data can't be accessed or modified directly only through controlled methods.
Example:
<!DOCTYPE html><html>
<body>
<script> function Student(name, marks) { var s_name = name; // private variable var s_marks = marks; // private variable
// Getter and Setter for 'name' Object.defineProperty(this, "name", { get: function () { return s_name; }, set: function (newName) { s_name = newName; } });
// Getter and Setter for 'marks' Object.defineProperty(this, "marks", { get: function () { return s_marks; }, set: function (newMarks) { s_marks = newMarks; } }); }
var stud = new Student("Ravi", 50); document.writeln(stud.name + " " + stud.marks); </script>
</body>
</html>
Output
.webp)
Key Point
- Encapsulation keeps data private and safe inside the object.
- Getters and setters control how data is accessed or updated.
- Helps create clear, secure, and maintainable code.