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