Do neither of those things.
Make a javascript "class":
var MyClass = function () {
var privateVar; //private
var privateFn = function(){}; //private
this.someProperty = 5; //public
this.anotherProperty = false; //public
this.someFunction = function () { //public
//do something
};
};
MyNamespace.MyClass = new MyClass();
One with static vars:
var MyClass = (function(){
var static_var; //static private var
var MyClass = function () {
var privateVar; //private
var privateFn = function(){}; //private
this.someProperty = 5; //public
this.anotherProperty = false; //public
this.someFunction = function () { //public
//do something
};
};
return MyClass;
})();
MyNamespace.MyClass = new MyClass();
With a "constructor" (all of the examples have a "constructor", this one just has parameters to work with):
var MyClass = function (a, b c) {
//DO SOMETHING WITH a, b, c <--
var privateVar; //private
var privateFn = function(){}; //private
this.someProperty = 5; //public
this.anotherProperty = false; //public
this.someFunction = function () { //public
//do something
};
};
MyNamespace.MyClass = new MyClass(1, 3, 4);
With all of the above you can do:
MyNamespace.MyClass.someFunction();
But you cannot do (from the outside):
MyNamespace.MyClass.privateFn(); //ERROR!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…