Encapsulation in JavaScript
Encapsulation is a principle of OOP that refers to the idea of bundling data and methods that operate on that data within a single unit (i.e., a class). In JavaScript, you can use closures to create private variables and methods.
Here's an example of how to use closures to create private variables and methods in JavaScript:
javascript
class Counter {
constructor() {
let count = 0;
this.increment = function() {
count++;
console.log(`Count: ${count}`);
}
this.decrement = function() {
count--;
console.log(`Count: ${count}`);
}
}
}
const counter = new Counter();
counter.increment(); // prints "Count: 1"
counter.increment(); // prints "Count: 2"
counter.decrement(); // prints "Count: 1"
No comments:
Post a Comment