google+javascriptbanktwitter@js_bankfacebook@jsbankrss@jsbank






Encapsulation en POO JavaScript L'encapsulation est une technique tr


Étiquette: La programmation orient

Gratuit iPage hébergement Web pour la première année MOMENT



Si vous êtes toujours à la recherche d'un fournisseur d'hébergement Web fiable avec des tarifs abordables, pourquoi vous ne prenez pas un peu de temps pour essayer iPage, seulement avec $1.89/month, inclus $500+ Crédits supplémentaires gratuites pour le paiement de 24 mois ($45)?

Plus de 1.000.000 de clients + existisng peuvent pas avoir tort, vraiment vous n'êtes pas aussi! Plus important encore, lorsque vous enregistrez l'hébergement web à iPage grâce à notre lien, nous allons être heureux de renvoyer un plein remboursement. C'est génial! Vous devriez essayer iPage hébergement web GRATUITEMENT maintenant! Et contactez-nous pour tout ce que vous devez savoir sur iPage.
Essayez iPage GRATUIT première année MOMENT

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.

iPhoneKer.com
Save up to 630$ when buy new iPhone 15

GateIO.gomymobi.com
Free Airdrops to Claim, Share Up to $150,000 per Project

https://tooly.win
Open tool hub for free to use by any one for every one with hundreds of tools

chatGPTaz.com, chatGPT4.win, chatGPT2.fun, re-chatGPT.com
Talk to ChatGPT by your mother language

Dall-E-OpenAI.com
Generate creative images automatically with AI

AIVideo-App.com
Render creative video automatically with AI

JavaScript par jour


Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web