Dino Geek, try to help you

How to encapsulate data in Node.js?


Encapsulation is one of the main principles of object-oriented programming. It allows an object to separate its interface from its implementation, meaning the data and the methods (or functions) that manipulate that data are bundled together.

In Node.js, you can create data encapsulation through different methods, like using classes, closures, and modules.

1. Using Classes:

You can create a class in Node.js using the `class` keyword. Here’s a simple example:

```
class User { constructor(name, age){ this.name = name; this.age = age; }

getName(){ return this.name; } getAge(){ return this.age; } }

let user1 = new User(“John”, 22);
console.log(user1.getName()); // John
console.log(user1.getAge()); // 22
```

In this example, `name` and `age` are encapsulated in `User` class, and they’re only accessible through the methods `getName` and `getAge`.

1. Using Closure:

A closure is a function that has access to its own scope, the outer function’s scope, and the global scope. We can create private variables/functions using closures that can provide data encapsulation.

```
function User(name, age) { this.getName = function() { return name; }

this.getAge = function() { return age; } }

let user1 = new User(‘John’, 22);
console.log(user1.getName()); // John
console.log(user1.getAge()); // 22
```

1. Using Module:

In Node.js, modules are also used to encapsulate data. Each module has its own context, so it cannot interfere with other modules. You can export from a module to make them accessible to other modules.

Here’s an example:

user.js:
```
let name = “John”;
let age = 22;

function getName() { return name;
}

function getAge() { return age;
}

module.exports = { getName, getAge };
```

app.js:
```
let user = require(‘./user.js’);

console.log(user.getName()); //John
console.log(user.getAge()); //22
```

In this example, `name` and `age` are encapsulated in the `user` module.


Simply generate articles to optimize your SEO
Simply generate articles to optimize your SEO





DinoGeek offers simple articles on complex technologies

Would you like to be quoted in this article? It's very simple, contact us at dino@eiki.fr

CSS | NodeJS | DNS | DMARC | MAPI | NNTP | htaccess | PHP | HTTPS | Drupal | WEB3 | LLM | Wordpress | TLD | Domain name | IMAP | TCP | NFT | MariaDB | FTP | Zigbee | NMAP | SNMP | SEO | E-Mail | LXC | HTTP | MangoDB | SFTP | RAG | SSH | HTML | ChatGPT API | OSPF | JavaScript | Docker | OpenVZ | ChatGPT | VPS | ZIMBRA | SPF | UDP | Joomla | IPV6 | BGP | Django | Reactjs | DKIM | VMWare | RSYNC | Python | TFTP | Webdav | FAAS | Apache | IPV4 | LDAP | POP3 | SMTP

| Whispers of love (API) | Déclaration d'Amour |






Legal Notice / General Conditions of Use