twitter@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.


Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web