You may want to use the Yahoo Module Pattern:
myModule = function () {
//"private" variables:
var myPrivateVar = "I can be accessed only from within myModule."
//"private" method:
var myPrivateMethod = function () {
console.log("I can be accessed only from within myModule");
}
return {
myPublicProperty: "I'm accessible as myModule.myPublicProperty."
myPublicMethod: function () {
console.log("I'm accessible as myModule.myPublicMethod.");
//Within myProject, I can access "private" vars and methods:
console.log(myPrivateVar);
console.log(myPrivateMethod());
}
};
}();
You define your private members where myPrivateVar
and myPrivateMethod
are defined, and your public members where myPublicProperty
and myPublicMethod
are defined.
You can simply access the public methods and properties as follows:
myModule.myPublicMethod(); // Works
myModule.myPublicProperty; // Works
myModule.myPrivateMethod(); // Doesn't work - private
myModule.myPrivateVar; // Doesn't work - private
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…