"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 the word "coupling". In fact, the effect of encapsulation is to understand the coupling, so that there is not too many links between classes and classes, to prevent one day to change a certain type of time, creating a "multi-metre 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.

In JavaScript, however, there is no built-in mechanism whatsoever. So we still need to do some processing, the same to imitate the package.

2. Ways to create objects


1) The simplest way is to open the portal to a large object. Use a function as its constructor. The so-called open door is the whole of his properties and methods are open. Equivalent to our frequently used keyword "public".


<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 one of the simplest ways to create objects. However, it is still unable 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) Read the above vb.net code. In fact, we can also imitate the implementation in JavaScript, or the above operation, define a book class. There are three properties for this class, so you can simply set a get method if you just want to. To differentiate between private and public members, you can underline methods 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 you can 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 visited.

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 implement an external function you can access the internal private variable                  }        //Set the private property of the Access object through the prototype 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 operations can encapsulate private properties of whatever object. 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 will not be discussed.

As for all of the methods to be created into the prototype object, no matter how small the object instance is generated. These methods only exist in memory, and the methods are shared. And one is different, and no object is generated. Does not call a method, it consumes a portion of memory. For example, the above example creates 5 book objects. Using the _getname method in sample one. Each object consumes a portion of memory and is created with a prototype object. Five book objects share a portion of memory, which is their most essential difference.

Suppose that the method created with the prototype object, when instantiating the Book1, runs the method, starts from this object, assumes that it is stopped, and then moves to the prototype object method to find it. This is why objects created can share the nature of the prototype object approach.

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 in JavaScript to create objects, in fact, in contrast to other languages, very simple. It just involves a few "closures" of knowledge, and if you use other languages, you'll be well-informed.


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

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.