tailieunhanh - Pro JavaScript Design Patterns 2008 phần 3

Vấn đề là JavaScript không có xây dựng theo cách của việc tạo ra hoặc thực hiện các giao diện. Nó cũng thiếu xây dựng trong các phương pháp để xác định xem một đối tượng thực hiện cùng một tập hợp các phương pháp như là một đối tượng khác, làm cho nó khó khăn để sử dụng các đối tượng thay thế cho nhau. | 40 CHAPTER 3 ENCAPSULATION AND INFORMATION HIDING It is possible to be too successful with encapsulation. If you don t have a clear understanding of how your classes may be used by other programmers actively preventing them from modifying the internal details may be too restrictive. It s hard to predict how people will use your code. Encapsulation could make your classes so inflexible that it is impossible to reuse them to achieve a purpose you hadn t anticipated. The biggest drawback is that it is hard to implement encapsulation in JavaScript. It requires complicated object patterns most of which are very unintuitive for novice programmers. Having to understand concepts such as the call chain and immediately executed anonymous functions adds a steep learning curve to a language that is already very different from most other object-oriented languages. Furthermore it can make existing code hard to decipher for someone not well-versed in a particular pattern. Descriptive comments and documentation can reduce this problem a bit but not eliminate it completely. If you are going to be using these patterns it is important that the other programmers you work with also understand them. Summary In this chapter we looked at the concept of information hiding and how to enforce it with encapsulation. Since JavaScript has no built-in way to do this you must rely on other techniques. Fully exposed objects are useful when it isn t crucial to maintain the integrity of internal data or when other programmers can be trusted to use only the methods described in the interface. Naming conventions can also help to steer other programmers away from internal methods that shouldn t be accessed directly. If true private members are needed the only way to create them is through closures. By creating a protected variable space you can implement public private and privileged members along with static class members and constants. Most of the later chapters in this book rely on these basic .

TỪ KHÓA LIÊN QUAN