Javascript design pattern-encapsulation and Information Hiding (lower)

Source: Internet
Author: User

Today, we will explain how to implement static methods and attributes in Advanced Patterns. There are other knowledge points about constants.
1. Static methods and attributes
In fact, we still need to use closures to implement this function. The third implementation method in the previous section also uses closures. However, internal attributes and methods are instance-level.
Var book1 = new Book ('isbn1 ', 'title1', 'author1 ');
Var book2 = new Book ('isbn2 ', 'title2', 'author2 ');

Alert (book1.getTitle (); // output title1
Alert (book2.getTitle (); // output title2
The above example shows that the created book1 and book2 have independent private attributes, and the assignment of values to the private attributes of book2 does not affect book1.
So how can we implement the class-level private attributes and methods? In addition to using closures, we also need to use anonymous functions. The Code is as follows: Code 1

Var Book = (function (){
// Private static attributes.
Var numOfBooks = 0;
// Private static method.
Function checkIsbn (isbn ){
...
}

// Return the constructor.
Return function (newIsbn, newTitle, newAuthor) {// implements Publication
// Private attributes.
Var isbn, title, author;
// Privileged methods.
This. getIsbn = function (){
Return isbn;
};
This. setIsbn = function (newIsbn ){
If (! CheckIsbn (newIsbn) throw new Error ('book: Invalid ISBN .');
Isbn = newIsbn;
};
This. getTitle = function (){
Return title;
};
This. setTitle = function (newTitle ){
Title = newTitle | 'no title specified ';
};
This. getAuthor = function (){
Return author;
};
This. setAuthor = function (newAuthor ){
Author = newAuthor | 'no author specified ';
};
This. getNumOfBooks = function (){
Return numOfBooks;
};

// Constructor code.
NumOfBooks ++; // Keep track of how many Books have been instantiated
// With the private static attribute.
If (numOfBooks> 50) throw new Error ('book: Only 50 instances of Book can be'
+ 'Created .');
This. setIsbn (newIsbn );
This. setTitle (newTitle );
This. setAuthor (newAuthor );
}
})();

// Public static method.
Book. convertToTitleCase = function (inputString ){
...
};

// Public, non-privileged methods.
Book. prototype = {
Display: function (){
...
}
};

If you are not familiar with anonymous functions, you can view relevant information on your own. In fact, the above Code is equivalent to: Code 2

Var tempBook = function (){
// Private static attributes.
Var numOfBooks = 0;
// Private static method.
Function checkIsbn (isbn ){
...
}
// Return the constructor.
Return function (newIsbn, newTitle, newAuthor) {// implements Publication
...
}
};

Var Book = tempBook ();

// Public static method.
Book. convertToTitleCase = function (inputString ){
...
};
// Public, non-privileged methods.
Book. prototype = {
Display: function (){
...
}
};

So what will happen if you execute the previous Code:
Var book1 = new Book ('isbn1 ', 'title1', 'author1 ');
Var book2 = new Book ('isbn2 ', 'title2', 'author2 ');
Alert (book1.getNumOfBooks (); // output 2
Alert (book2.getNumOfBooks (); // output 2
Why is there such an effect? In fact, numOfBooks is already a real private static variable through the combination of anonymous functions and closures, no matter how many Book instances you create, there is only one numOfBooks variable in the system. Some people may wonder why one numOfBooks is not generated every time a new Book instance is created?
We can find the answer from code 2. In fact, the created Book instance executes the tempBook () method instead of the new tempBook object! The tempBook object runs only once in the system, so there is only one copy of its internal numOfBooks variable. Execute new Book ('... ','... ','... '); actually, only the function (newIsbn, newTitle, newAuthor) in the tempBook is executed, and no new tempBook object is created, all Book instances call the same numOfBooks method when using the getNumOfBooks method.
I don't know if my explanation is clear. I hope it will help you.
2. Constants
In fact, there is nothing to say about this part. As long as you understand the above content, implement a variable similar to numOfBooks in the anonymous function and do not modify it throughout the initialization process, no modification method is provided, and a method similar to the getNumOfBooks method is provided for external access. Then, the code is OK, and I am too lazy to write it.
3. advantages and disadvantages of using Encapsulation
Benefits:
You can control the code and publish information that you want to disclose. It is also convenient for you to refactor the code. The user of the object you create will not affect the normal use of others because you modify the internal object (private variable or method. Surface-to-surface interface programming can achieve loose coupling between codes. Www.2cto.com
Disadvantages:
1. It is difficult to test internal variables. The best way is to test internal methods by testing public methods.
2. Code debugging becomes difficult due to complicated scopes.


Author: kbh1983

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.