JavaScript design pattern-Prelude (encapsulation and Information Hiding)

Source: Internet
Author: User

JavaScript design pattern-Prelude (encapsulation and Information Hiding)
3. encapsulation and Information Hiding: Information Hiding is used for decoupling and defining private data and methods. Encapsulation is a technology used to hide information. It defines and uses private data through closures. The interface plays a role in this: provides a contract that records public access methods, and defines the relationships between two objects. Next, we will introduce the basic mode for object creation: There are three basic modes: The portal is large-sized, the private usage of methods and attributes is expressed with underscores, And the closure is used to create private members. For example, you need to create a Book class, and others will create and use the instance. // Book (isbn, title, author) var theHobbit = new Book ('0-12-34-2654-2 ', 'the hobb', 'sin'); theHobbit. display (); 1. portal wide-opening: the so-called portal wide-opening, that is, using a function as the constructor, all methods and attributes are open.

1 // define Interface 2 var Publication = new Interface ('publication ', ['getisbn', 'setisbn ', 'gettitle', 'settitle', 'getauthor ', 'setauthor', 'display']); 3 4 // implements Publication 5 var Book = function (isbn, title, author) {6 this. setIsbn (isbn); 7 this. setTitle (title); 8 this. setAuthor (author); 9} 10 Book. prototype = {11 checkIsbn: function (isbn) {12 //..... check whether the isbn format is Standard 13 //....... 14}, 15 getIsbn: function () {16 re Turn this. isbn; 17}, 18 getTitle: function () {19 return this. title; 20}, 21 getAuthor: function () {22 return this. author; 23}, 24 setIsbn: function (isbn) {25 if (! This. checkIsbn (isbn) throw new Error ('book: Invalid ISBN '); 26 this. isbn = isbn; 27}, 28 setTitle: function (title) {29 this. title = title | "no title specified"; 30}, 31 setAuthor: function (author) {32 this. author = author | "no author specified"; 33}, 34 display: function () {35 //.............. 36 alert (this. getIsbn () + this. getTitle () + this. getAuthor () 37} 38

 

This method seems perfect, but the attributes in it can still be modified. isbn may also be assigned an invalid value. 2. Using a function as the constructor (using naming rules to distinguish Private Members) is the same as the preceding method, which is to underline private members. I will not discuss it in detail. 3. Scope, nesting, and closure
1 // implements Publication 2 var Book = function (newisbn, newtitle, newauthor) {3 // Private Member 4 var isbn, title, author 5 6 // Private Method 7 function checkIsbn (isbn) {8 //..... check whether the isbn format is standard 9 //....... 10} 11 12 // privileged method 13 this. getIsbn () {14 return isbn; 15} 16 this. getTitle () {17 return title; 18} 19 this. getAuthor () {20 return author; 21} 22 this. setIsbn () {23 if (! CheckIsbn (newisbn) throw new Error ('book: Invalid ISBN '); 24 isbn = newisbn; 25} 26 this. setTitle () {27 title = newtitle; 28} 29 this. setAuthor () {30 author = newauthor; 31} 32 33 // construct 34 this. setIsbn (newisbn); 35 this. setAuthor (newauthor); 36 this. setTitle (newtitle); 37} 38 39 Book. prototype = {40 display: function () {41 //.............. 42}

 

This method has a problem. In the previous method object Creation Mode of the portal large-size method, all methods are created on the prototype object. Therefore, no matter how many object instances are generated, these methods only exist in the memory. This method generates a new copy for every private and privileged method every time a new object instance is generated. This will waste more memory. This object creation mode is not conducive to subclass derivation. (Inheritance destroys encapsulation .....) summary: Private attributes and Methods: The function has a scope. variables declared using the var keyword in the function cannot be accessed externally, private attributes and methods are essentially variables that you want to be inaccessible outside the object. Privileged attributes and Methods: this keyword is used to create attributes and Methods. Because these methods are defined in the scope of the constructor, they can access private attributes and methods; only methods that require direct access to private members should be designed as privileged methods. Common attributes and Methods: directly link the attributes and methods on prototype. You cannot access private members in the constructor or privileged members. Subclass inherits all common methods. Static attributes and methods: the best way to understand it is to think of it as a namespace, which is actually equivalent to using the constructor as a namespace.
1/* -- encapsulate -- */2 var classA = function () {3 // Private attributes and Methods 4 var name = 'sin'; 5 var method1 = function () {6 //... 7} 8 // privileged attributes and Methods 9 this. age = '20'; 10 this. getName = function () {11 return name; 12} 13} 14 // a total of static attributes and Methods 15 classA. _ name = 'darren Code'; 16 classA. alertName = function () {17 console. log (_ name); 18} 19 // total attributes and Method 20 classA. prototype = {21 init: function () {22 //..... 23}, 24 init2: function () {25 //..... 26} 27}

 

Iv. Inheritance: 1. class inheritance (combination inheritance)
1 // super class (parent class) 2 function Persion (name) {3 this. name = name; 4} 5 Persion. prototype. getName () {6 return this. name; 7} 8 9 // (subclass) 10 function Author (name, books) {11 Persion. call (this, name); // call the superclass constructor and pass the name as a parameter 12 this. books = books; 13} 14 Author. prototype = new Persion (); // the prototype of the sub-class points to the super class instance, and the sub-class prototype points to the memory's methods and attributes. 15 Author. prototype. constructor = Author; // prototype because the prototype object of the subclass is equal to the superclass instance. constructor: This method is also equivalent to a superclass constructor. Therefore, you must specify constructor.16 Author again. prototype. getBooks = function () {17 return this. books; 18}

 

Create a constructor first, then create a subclass, and call (this, arguments) to call the constructor. Then set the prototype chain. js does not have extend, so ...... it uses prototype for inheritance. For prototype, read the book by yourself if you don't understand it ...... be solid ........ the prototype of the subclass is an instance, which will have the prototype attribute of the parent class. Then, the prototype of the parent class is used to find the methods or attributes in the memory. To simplify the declaration of classes, you can wrap the entire process of the derived subclass in an extend function. 1 function extend (subClass, superClass) {2 var F = function () {}; 3 F. prototype = new superClass. prototype; 4 subClass. prototype = new F (); 5 subClass. prototype. constructor = subClass; 6} however, this eventually has a problem. That is, the super class name (Person) is solidified in the Author class declaration ....... it's so uncomfortable ..................... but there is a better way
1 function extend (subClass, superClass) {2 var F = function () {}; 3 F. prototype = new superClass. prototype; 4 subClass. prototype = new F (); 5 subClass. prototype. constructor = subClass; 6 7 subClass. superclass = superClass. prototype; // Add the superclass attribute 8 if (superClass. prototype. constructor = Object. prototype. constructor) {9 superClass. prototype. constructor = superClass; // -------- OK ???? I don't know how to read it myself ..... I don't know much about it either ...... 10} 11} 12 13 function Author (name, books) {14 Author. superclass. constructor. call (this, name); 15 this. books = books; 16} 17 extend (Author, Persion); 18 Author. prototype. getBooks = function () {19 return this. books; 20}

 

With the superclass attribute, you can directly call methods in the superclass. Where are its benefits? Hahaha .... when you want to redefine a method with the same name as the superclass method, you can use the superclass attribute to call the original method with the same name and then process it. 1 Author. prototype. getName = function () {2 var name = Author. superclass. constructor. getName. call (this); // Why should I add a call? Alas... I don't understand it anymore .. it is true (of course it is the scope of this, and the name attribute of Author should be taken) 3 return name + ", Author of" + this. getBooks (). join (','); 4} // class inheritance uses the prototype chain .... study the prototype chain by yourself ..... 2. original Type inheritance
1/* -- original type inheritance -- */2 // use the clone () function to create a new class Person object 3 var clone = function (obj) {4 var _ f = function () {}; 5 // This sentence is the core of the original type inheritance. The prototype object of the function is 6 _ f. prototype = obj; 7 returnnew _ f; 8} 9 // declare an object literally 10 var Person = {11 name: 'darren', 12 getName: function () {13 returnthis. name; 14} 15} 16 // no need to define a Person subclass. You only need to execute a clone operation to perform 17 var Programmer = clone (Person ); 18 // you can directly obtain the default value provided by Person, or you can add or modify attributes and Methods 19 alert (Programmer. getName () 20 Programmer. name = 'darren2' 21 alert (Programmer. getName () 22 23 // declare the subclass. Run a clone operation to 24 var Someone = clone (Programmer );

 

Summary: class inheritance (combination inheritance): uses the prototype chain to inherit shared attributes and methods, and uses the call (_, _) to inherit instance attributes. original Type inheritance: inheritance can be implemented without pre-defining constructors. The essence of inheritance is to execute a shortest copy of a given object. The copied copy can be further transformed. Parasitic inheritance: parasitic combined inheritance: class inheritance, the prototype of the subclass points to an instance of the parent class; original type inheritance, the prototype of the subclass points to an object literal of the parent class (Shortest copy ). (Subclasses may modify attributes and methods of the parent class .) The original type inheritance saves more memory: The cloned objects share the unique instance of each attribute and method. Each object created by class inheritance has its own set of attributes (and private methods) in the memory.

Related Article

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.