JavaScript uses decorative simulation to implement private state

Source: Internet
Author: User

In the classical object-oriented programming, it is often necessary to encapsulate or hide a state of an object in the object, only through the object's amplitude and access to these states, exposing only some important state variables can read and write directly.

We can simulate implementing a private instance field by decorating the variable (or parameter) within a constructor, and invoking the constructor creates an instance.

function Range ( from, to) {    //do not save the battle as an object's property, instead//define accessor functions to return the value of the endpoint//These values are saved in the closure     This. from=function () {return  from;}  This. To=function () {returnto ;}} Range.prototype={constructor:range, includes:function (x) {return  This. from() <=x && x<= This. to ();},foreach: function (f) { for(varX=math.ceil ( This. from()), max= This. to (); x<=max;x++;) f (x); }, Tostring:function () {return "("+ This. from() +"..."+ This. to () +")"; }}//Call:varR=NewRange (0,5);//a range that cannot be modifiedR. from=function () {return 0; }//to modify it by this method

It is important to note that this encapsulation technology creates more overhead for the system. Classes that use closures to close the state of a class must run slower and consume more memory than equivalent classes that do not use encapsulated state variables.

From the JavaScript Authority guide 9.6.6

JavaScript uses decorative simulation to implement private state

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.