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

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).

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