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

Real encapsulation, the hard way

For real encapsulation, the following criteria need to be met:

  • You must be able to define private properties within the constructor and methods.
  • You must be able to access and manipulate the private properties within the constructor and methods.
  • The private properties must not be directly accessible from outside (i.e. as properties on the instance).

To fulfill these criteria we're going to need to create a small abstraction that will enable us to define our constructor, its methods, and its properties in a plain object, which will then be processed to produce the required constructor and prototype.

In accordance with convention, this abstraction will be named Class. This is how it will typically work:

var Person = new Class({

 
    _name: 'Blank',
    _age: 0,
 
    init: function(name, age) {

        this.name = name;
        this.age = age;

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

    },
 
    setAge: function(age) {
        this.age = age;

    },
 
    setName: function(name) {
        this.name = name;

    }
 
});

The underscore prefix tells Class that we want those properties to be private. Privacy is achieved by retaining a truly private (in a closure) privates array, each item within the array represents the private properties of each instance. This will be clearer once you've seen the source (below).

Class looks for an init method to use as the constructor.

Here's the source for Class, excluding the function:

function Class(o){
 
    var id = 0,

        privates = {},
        instancePrivates = [],
        constructor = function(){

 
            this.__id = id++;
 
            // Copy privates over to new privates obj,
            // just for this instance.
            instancePrivates[this.__id] = {

                privates: merge({}, privates),
                constructor: this

            };
 
            if (this.init) {
                this.init.apply(this, arguments);

            }
 
            return this;
 
        },
        m;

 
    function method(name, fn) {
 
        constructor.prototype[name] = function() {

 
            var i, ret,
                thisPrivates = instancePrivates[this.__id] || {};

 
            // Check constructor
            if (thisPrivates.constructor !== this) {

                // this.__id has been changed, exit.
                return;
            }
 
            thisPrivates = thisPrivates.privates;

 
            for (i in thisPrivates) {
                this[i] = thisPrivates[i];

            }
 
            ret = fn.apply(this, arguments);

 
            for (i in thisPrivates) {
                thisPrivates[i] = this[i];

                delete this[i];
            }
 
            return ret;

 
        };
 
    };
 
    for (m in o) {

 
        // Test for privates
        if ( /^_/.test(m) ) {

 
            privates[m.replace(/^_/, '')] = o[m];

 
        } else {
 
            method(m, o[m]);

 
        }
 
    }
 
    return constructor;
 
}

There are cleaner ways of implementing this, but just for readability's sake, we're identifying each instance with a simple __id property. Yes, this can be manipulated from the outside, but doing so would result in the methods not running.

It has some constraints, but it does provide us with encapsulation:

var Person = new Class({

 
    _name: 'Blank',
    _age: 0,
 
    init: function(name, age) {

        this.name = name;
        this.age = age;

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

    },
 
    setAge: function(age) {
        this.age = age;

    },
 
    setName: function(name) {
        this.name = name;

    }
 
});
 
// Testing:
 
var jimmy = new Person('Jim', 88);

 
jimmy._name; // undefined
jimmy.name; // undefined
 
jimmy.toString(); // => "Name: Jim, Age: 88"

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

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

 
jimmy._age; // undefined
jimmy.age; // undefined

You can also have private methods, e.g.

var Box = new Class({
 
    _width: 0,

    _height: 0,
 
    init: function(width, height) {

        this.width = width;
        this.height = height;

    },
 
    info: function() {
        return 'Width: ' + this.width +

                ',\nHeight: ' + this.height +
                ',\nArea: ' + this.calcArea();

    },
 
    _calcArea: function() {
        return this.width * this.height;

    }
 
});
 
var myBox = new Box(100, 100);

 
myBox.calcArea; // undefined
myBox._calcArea; // undefined
 
myBox.info(); // => "Width: 100,\nHeight: 100,\nArea: 10000"

Conclusion

The method I used to achieve full encapsulation, while quite novel, isn't going to be appropriate in all situations. The population and clearing of private variables has to happen on every method call, and so will likely cause a significant overhead in some applications.

That said, I don't think the overhead will be all that significant, unless you've got a crazy amount of private properties/methods.

I hope this post has given you some insight into how you can achieve encapsulation and information-hiding in JavaScript.

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

AI Voice Generator
Most Realistic Text to Speech AI Solutions

AI Voice Generator
Most Realistic Text to Speech AI Solutions

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

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