google+javascriptbanktwitter@js_bankfacebook@jsbankrss@jsbank






Đóng gói trong OOP JavaScript Đóng gói là kĩ thuật cực kì hữu ích trong lập trình hướng đối tượng, công dụng chủ yếu của nó là cho phép lập trình viên tách rời việc cài đặt và định nghĩa giữa các lớp trừu tượng và lớp giao diện. Trong bài viết này, James Padolsey sẽ hướng dẫn bạn thực hiện việc đóng gói trong ngôn ngữ lập trình JavaScript, vui lòng vào bài viết chi tiết để xem thêm.


Miễn phí web hosting 1 năm đầu tại iPage



Nếu bạn vẫn còn đang tìm kiếm một nhà cung cấp hosting đáng tin cậy, tại sao không dành chút thời gian để thử với iPage, chỉ với không quá 40.000 VNĐ/tháng, nhưng bạn sẽ được khuyến mãi kèm với quà tặng trị giá trên 10.000.0000 VNĐ nếu thanh toán cho 24 tháng ~ 900.000 VNĐ?

Có trên 1 triệu khách hàng hiện tại của iPage đã & đang hài lòng với dịch vụ, tuyệt đối chắc chắn bạn cũng sẽ hài lòng giống họ! Quan trọng hơn, khi đăng ký sử dụng web hosting tại iPage thông qua sự giới thiệu của chúng tôi, bạn sẽ được hoàn trả lại toàn bộ số tiền bạn đã sử dụng để mua web hosting tại iPage. Wow, thật tuyệt vời! Bạn không phải tốn bất kì chi phí nào mà vẫn có thể sử dụng miễn phí web hosting chất lượng cao tại iPage trong 12 tháng đầu tiên. Chỉ cần nói chúng tôi biết tài khoản của bạn sau khi đăng ký.

Nếu muốn tìm hiểu thêm về ưu / nhược điểm của iPage, bạn hãy đọc đánh giá của ChọnHostViệt.com nhé!
Thử iPage miễn phí cho năm đầu tiên NGAY

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 theo ngày


Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web