Say nothing more, directly on the code, see the original author comments go, uh ...
Static private variables
The code is as follows |
Copy Code |
var mynamespace = {}; Defining namespaces Mynamespace.treeitem = (function () { Private static variables generated using closures are not accessible externally var numtreeitems = 0; Private static methods that are generated using closures are not accessible externally function counter () { Numtreeitems + +; Console.log ("Created" +numtreeitems+ "Tree items!"); } The reference to the anonymous function is given to Mynamespace.treeitem return function () { Private class variables generated using closures are not accessible externally var label; A method that can access private variables or be accessed externally This.setlabel = function (Newlabel) { label = Newlabel; }; This.getlabel = function () { return label; }; The method used to accumulate the number of instances Counter (); } })(); Add parentheses at the end of the function definition to indicate that the function executes immediately after the definition Static public methods that do not have access to private variables and other public methods MyNamespace.TreeItem.clone = function (otherinstance) { }; MyNamespace.TreeItem.prototype = { Public methods that do not have access to private variables but can access other public methods Print:function () { Console.log (This.getlabel ()); } }; var treeItem1 = new Mynamespace.treeitem (); Print 1 var treeItem2 = new Mynamespace.treeitem (); Print 2 Analog constants This constant class is used to hold all final static constants in the application var Constant = (function () { Closed-Package private static variables that cannot be accessed externally var constants = { version:7.5 }; Constructors var constructor = function () { }; Methods that can be accessed externally, and also access private static variables within a closure constructor.getconstants = function (name) { return Constants[name]; }; return constructor; })(); Accessing static constants in a constant closure Constant.getconstants (' VERSION '); Return 7.5 |
Each new TreeItem instance is created, and the memory opens up the physical space for its private variables, private methods, and all methods that access both private and private methods, while the methods in prototype always have only one