Getter () and setter () methods for private properties of closures implemented in JavaScript

Source: Internet
Author: User

Attention:

The following output is in the browser's console

<! DOCTYPE html>/** * using closures to implement * This function adds an attribute memory method to the object O * method names are get<name> and set<name>. If a judgment function is provided, the setter method will use it to detect the legitimacy of the parameter and then store it * If the decision function returns the False,setter method throws an exception * * This function has getter and setter functions * The value of the property being manipulated is not stored in object o * want to inverse, this value is only stored in the function of the local variable * getter and setter method is also a local function, so you can access the local variable * that is, two accessor methods to set or or modify this value*/functionAddprivateproperty (o,name,predicate) {varValue//This is a property value    //The getter method simply returns it to theo[' Get ' +name] =function(){returnvalue;}; //the Setter method first checks the value to demonstrate legality and throws an exception if it is not legal    //otherwise, store it.o[' Set ' +name] =function(v) {if(Predicate &&!)predicate (v))ThrowError (' Set ' +name+ ': Invalid value ' +v); Elsevalue=v; };}//wanted code to show the Addprivateproperty () methodvaro = {};//set an empty object//Add attribute Memory Methods GetName () and SetName ()//ensure only word order string valuesAddprivateproperty (O, "Name",function(x) {return typeofx=== "string";}); O. SetName ("Frank");//Setting property valuesConsole.log (O.getname ());//Get Property valueTry{o.setname (0);//setting a non-character value throws an error (thrown by the throw statement)}Catch(e) {Console.log ("Property value setting error");//The above throws the error here to the processing}</script></body>

Getter () and setter () methods for private properties of closures implemented in JavaScript

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.