google+javascriptbanktwitter@js_bankfacebook@jsbankrss@jsbank






Encapsulation en POO JavaScript L'encapsulation est une technique tr


�tiquette: La programmation orient

G�n�rez vos vid�os d'entreprise par l'IA avec la voix ou simplement du texte



Votre premi�re application vid�o AI GRATUITE ! Automatisez votre premi�re vid�o AI. Cr�ez votre vid�o professionnelle en 5 minutes gr�ce � l'IA. Aucun �quipement ni comp�tence en montage vid�o requis. Production vid�o sans effort pour les sp�cialistes du marketing de contenu.
Application vid�o AI ILLIMIT�E gratuite � port�e de main

Encapsulation is a useful technique in programming which allows you to separate an abstraction's implementation from its interface, thus enabling future changes to the implementation without affecting the interface. There are other benefits of encapsulation, such as:

  • Being able to screen (validate) new properties, via setter methods.
  • Being able to process properties before their "release", via getter methods.
  • Making your abstraction less prone to abuse by other developers - specifically, to protect private variables and states that could compromise the effectiveness of the abstraction.

Grady Booch (author of "Object Oriented Analysis and Design") describes encapsulation as:

"The process of compartmentalizing the elements of an abstraction that constitute its structure and behavior; encapsulation serves to separate the contractual interface of an abstraction and its implementation."

JavaScript is often considered a toy that doesn't know of complex design patterns or have the capacity to support techniques such as encapsulation, but, contrary to misinformed belief, JavaScript does have capacity for encapsulation. It's just quite tricky, that's all!

Hiding your variables in closures

It's possible to hide variables in JavaScript. To make this happen we take advantage of the closure:

function Person(name, age) {

 
    this.toString = function() {
        return 'Name: ' + name + ', Age: ' + age;

    };
 
}

If you're not sure what a closure is just think of it as a function defined within another function. The "child" function has access to the "parent" function's scope.

You can see that we're defining the toString method within the constructor.

The only reason to define a constructor's methods anywhere other than its prototype, is in the situation where that method needs access to variables defined in the constructor's scope. Above, the toString method needs access to the variables, name and age.

Setters (and getters)

Once we instantiate this constructor (new Person('Jim', 88);), there's no way to change the name or age - they're "hard-coded" in the inaccessible "parent" scope.

We can make it possible to change these values by adding a couple of setter (AKA, mutator) methods:

function Person(name, age) {

 
    this.toString = function() {
        return 'Name: ' + name + ', Age: ' + age;

    };
 
    this.setName = function(newName) {

        name = newName;
    };
 
    this.setAge = function(newAge) {

        age = newAge;
    };
 
}
 
var jimmy = new Person('Jim', 88);

 
jimmy.toString(); // => "Name: Jim, Age: 88"
 
jimmy.setName('Jimmy');

 
jimmy.toString(); // => "Name: Jimmy, Age: 88"

This works perfectly, although there are a couple of points to discuss.

First, defining a bunch of methods in the constructor takes quite a bit of room and with a few more setter methods (and getters) the constructor can easily transform into a hard-to-read and hard-to-maintain piece of code. Semantically, this solution fails - a constructor should only contain what's needed to create an instance - ideally, this shouldn't include a bunch of method definitions.

Secondly, it's slow. Redefining a bunch of functions upon every single instantiation isn't going to be as fast as keeping all the methods in the prototype.

So, either we reach a compromise or we forget about real encapsulation, and settle for something a little less secure. For example, we could define all the getters and setters in the prototype and store our "privates" as public properties, but prefix them with an underscore or some other symbol to signify their private nature:

function Person(name, age) {

 
    this._name = name;
    this._age = age;

 
}
 
Person.prototype.toString = function() {

    return 'Name: ' + this._name + ', Age: ' + this._age;

};
 
Person.prototype.setName = function(newName) {

    this._name = newName;
};
 
Person.prototype.setAge = function(newAge) {

    this._age = newAge;
};

Our constructor is now a lot simpler and the setters work as required. The only issue with this approach is that there's no real information-hiding going on. Developers using the abstraction can still access the "implementation" (the private state).

AIVideo-App.com
Générez vos vidéos d'entreprise par l'IA avec la voix ou simplement du texte

chatGPTaz.com
Parlez à ChatGPT dans votre langue maternelle

AppAIVidéo
Votre première application vidéo AI GRATUITE

Deepfake Video
Deepfake AI Video Maker

Deepfake
Deepfake AI Video Maker

AI Deep Fake
Deepfake AI Video Maker

AIvidio
AI Video Mobile Solutions

AIvideos
AI Video Platform & Solutions

AIvedio
AI Video App Maker

Artificial General Intelligence
Ai and higher level Artificial General Intelligence (AGI)

Artificial General Intelligence
Ai and higher level Artificial General Intelligence (AGI)

Faceswap AI en ligne
Échangez des visages, des vidéos, des photos et des GIF instantanément avec de puissants outils d'IA - Faceswap AI Online GRATUIT

Faceswap AI en ligne
Échangez des visages, des vidéos, des photos et des GIF instantanément avec de puissants outils d'IA - Faceswap AI Online GRATUIT

Faceswap AI en ligne
Échangez des visages, des vidéos, des photos et des GIF instantanément avec de puissants outils d'IA - Faceswap AI Online GRATUIT

Powerful AI Presentation PPT Maker for FREE
Build an impressive presentation with our free online AI presentation app

Your next top AI Assistant
Claude AI, developed by Anthropic

Your next top AI Assistant
Claude AI, developed by Anthropic

Temu gratuit 500 $ pour les nouveaux utilisateurs
Claim Free Temu $500 Credit via Affiliate & Influencer Program

Crédits publicitaires TikTok gratuits
Maîtrisez les publicités TikTok pour le marketing de votre entreprise

Dall-E-OpenAI.com
Générez automatiquement des images créatives avec l'IA

chatGPT4.win
Parlez à ChatGPT dans votre langue maternelle

Premier produit d'intelligence artificielle d'Elon Musk - Grok/UN.com
Parlez au chatbot Grok AI dans votre langue

Outily.win
Centre d'outils ouvert et gratuit, utilisable par tous et pour tous, avec des centaines d'outils

GateIO.gomymobi.com
Airdrops gratuits à réclamer et à partager jusqu'à 150 000 $ par projet

iPhoneKer.com
Économisez jusqu'à 630 $ à l'achat d'un nouvel iPhone 16

Acheter le robot Tesla Optimus
Commandez votre robot Tesla Bot : Optimus Gen 2 dès aujourd'hui pour moins de 20 000 $

JavaScript par jour


Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web