"JavaScript design mode" Reading Notes II (encapsulation and hidden information)

Source: Internet
Author: User

1. Why encapsulation and information hiding


Friends who have done programming know that the word "coupling", in fact, the effect of encapsulation is to understand the coupling, so that the class and the class does not have too many links, to prevent one day to modify a certain type of time, resulting in "multi-meter bone Connaught card effect."

We can think of information hiding as a goal, and packaging as a technology to achieve information hiding. Encapsulation allows the object's internal data representation and implementation details to be hidden. It's like you can watch TV, but you don't know the internal structure of TV. But there is no built-in mechanism in JavaScript, so we need to do some processing to mimic encapsulation as well.

2. Ways to create objects


1) The simplest way is to open a portal object and use a function as its constructor. The so-called Portal Open is his all the properties and methods are public, the equivalent of our regular use of the key word "common".


<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" > <script>        //define a book class, function takes on the work of the constructor        var book = function (name, title, author) {            this.name = name;//titles            this.title = title;//title            This.author = author;//author        }        //Instantiate a Book1 object        var Book1 = new Book ("Language");        alert (book1.name);    </script></span>

This is the simplest way to create an object, but it is still not able to hide the information inside the object. Think about how we create objects in other programming languages?


2) Create a Property object in vb.net


<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;"    > ' Define a book class public class books Dim books As String ' titles Dim title As String ' title Dim author As String ' author ' <summary> ' get the title ' </summary> ' <value></value> ' <returns></retu Rns> ' <remarks></remarks> Property GetBook () as a String Get Return book En D Get Set (value as String) book = value End Set End Property ' <summary> ' returns t Itle ' </summary> ' <value></value> ' <returns></returns> ' <remarks&  Gt;</remarks> Property GetTitle () as String get Return title End get Set (value as String) title = value End Set End Property ' <summary> ' ' Get author ' ' </summary&gt    ; "<value></value>" <returns></returns> "<remarks&"Gt;</remarks> Property Getauthor () as String get Return author End get Set (value As String) Author = value End Set End Propertyend class</span>





3. Using closures to mimic vb.net constructors


1) Look at the above vb.net code, in fact, we can also be in JavaScript to imitate the implementation, or the above operation, define a book class, about this class has three properties, if you only want to get, you can simply set a GET method. To differentiate between private and public members, you can underline the method and property names by underlining them.


<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" > </span><pre class= "javascript" name= "code" ><span style= "font-family:simsun;font-size:18px;" >//defines a book class, function takes on the constructor work        var = function (name) {            this._name = name;//title            //through an inline function, To implement an external function to access the internal private variable            this._getname = function () {                return this._name;            }            This._setname = function (value) {                this._name=value            }        }        //Instantiate a Book1 object        var book1 = new book ("Language") );        Alert (Book1._getname ());//correct        book1._setname ("mathematics");        Alert (Book1._getname ());//correct        alert (_name);//Error Action        alert ("");</span>

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" > This is a simple closure that uses inline functions to return the private variables of the outer function, which encapsulates the private variables of the intrinsic functions and can be accessed. Have knowledge about closures, can see my previous blog. </span>


2) The above operation can also be achieved by the operation of the prototype object.


<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" ><script>        //define a book class, function takes on the constructor's work        var = function (name) {            This._name = name;//title            //through an inline function to enable external functions to access the internal private variables                  }        Use the prototype object to set the private property of the Access object        Book.prototype = {            _getname:function () {                return this._name;            },            _setname: function (value) {                this._name = value;            }        }        Instantiate a Book1 object        var book1 = new book ("Language");        Alert (Book1._getname ());//correct        book1._setname ("mathematics");        Alert (Book1._getname ());//correct        alert (_name);//Error Operation        alert ("");    </script></span>


3) Comparison of two methods


You can see that both of these actions can encapsulate the private properties of any object, and then again, what is the difference between these two operations?

This involves knowledge about prototype objects, and this section is just a simple implementation of how to encapsulate hidden information and not be discussed. As for the creation of all methods into the prototype object, regardless of the generation of a few object instances, these methods in memory only one copy, the method is common, and the other is different, did not generate an object, do not call a method, will occupy a portion of memory. For example, 5 book objects were created in the examples above. With the _getname method in example one, each object will occupy a portion of memory, and with the prototype object created, five book objects share a memory, which is their most essential difference.

If a method is created with a prototype object, when the Book1 is instantiated, the method is first searched from this object, if it is found then stopped, and not found is transferred to the prototype object method, which is why the object created can share the nature of the prototype object method.

Demo

function person (name, sex) {            this.name = name;            This.sex = sex;        }        Person.prototype.age =;        var Zhang = new person ("Zhangsan", "man");        Console.log (Zhang.age);        //Overwrite The age attribute in prototype        zhang.age = +;        Console.log (Zhang.age);        Delete zhang.age;        After the instance attribute age is removed, this property value is also obtained from prototype        Console.log (zhang.age);//20


4. Summary


The above is the way to imitate constructors to create objects in JavaScript, which is very simple compared to other languages. It only involves some "closures" of knowledge, if used in other languages, then you will be very mastered.


"JavaScript design mode" Reading Notes II (encapsulation and hidden information)

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.