Aby uniknąć zaśmiecania globalnej przestrzeni nazw, używam strukturę tak:
var MyLib = {
vars: {
var1: 'value1',
var2: 'value2'
},
func1: function() {
return this.vars.var1;
},
func2: function() {
alert("This is func2");
}
};
MyLib.func1();
MyLib.func2();
Zauważysz umieściłem wszystkie zmienne do własnej sub-object, odbywa się to wyłącznie do łatwe czytanie i rozwój.
EDIT 1:
Oto kolejny metoda używam
var MyLib = (function MyLib() {
var _privateVars = {
"someVar": "This value made public by `someMethod`",
"privateVar": "Can't see this value"
};
// Return the constructor
return function MyLibConstructor() {
var _this = this; // Cache the `this` keyword
_this.someMethod = function() {
// Access a private variable
return _privateVars.someVar;
};
_this.someOtherMethod = function() {
// Some other functionality
};
};
}());
var myLib = new MyLib(); // invoke
console.log(myLib.someMethod());
Struktura ta wykorzystuje JS Closures i funkcją konstruktora, więc jej łatwe do utrzymania w zmiennych prywatnych prywatne.
EDIT 2:
Ponadto, jakie stosuje się również inne ustawienia zamknięcia, które nie zwraca konstruktor (np var x = new MyLib();
).
(function(window) {
var _private = {},
methods = {},
topic, init;
methods.set = function(value) {
// Set the property & value
_private[topic] = value;
return this;
};
// A simple get method
methods.get = function(callback) {
var response = null;
// Return the value of topic (property) in a callback
if (!!callback && typeof callback === 'function') {
if (_private.hasOwnProperty(topic)) {
response = _private[topic];
}
callback.call(this, response);
}
return this;
};
// Init method setting the topic and returning the methods.
init = function(_topic) {
topic = _topic;
return methods;
};
// Exposure when being used in an AMD environment, e.g. RequireJS
if (typeof define === 'function' && define.amd) {
define(function() {
return init;
});
return;
}
// Exposure when being used with NodeJS
if ('undefined' !== typeof module && module.exports) {
module.exports = init;
return;
}
// Last-in-the-line exposure to the window, if it exists
window.myLib = init;
// This line either passes the `window` as an argument or
// an empty Object-literal if `window` is not defined.
}(('undefined' !== typeof window) ? window : {}));
I aby zobaczyć go w akcji:
myLib('something').set('made public, outside of the closure by the `get` method');
myLib('something').get(function(a){
console.log(a);
});
Proszę również spojrzeć na drodze ja wystawiając myLib
, biorąc pod uwagę, gdzie jest prowadzony i jak to jest włączone.
EDIT 3 (7/2017):
Jako pełnoprawny stosie (w/node.js) inżynier JavaScript, a nadejście Browserify, w pełni polecam korzystanie z Nodejs stylu module
wzór wykorzystanie Gulpa lub Grunta jako systemu kompilacji do kompilowania wielu plików (odsprzęgniętych, mniejszych bitów kodu) do jednej biblioteki.
Model ten zachęca do bardziej funkcjonalnego podejścia, pozwalając programistom na upowszechnienie bardziej popularnych funkcji w bibliotece w osobnych plikach, co znacznie ułatwia rozwój.
Och, i użyj ES6!
// file: src/divideIntByFour.js
const divideIntByFour = (int) => {
return int/4;
};
module.exports = divideIntByFour;
... Jako siplified przykład
Myślę, że powinieneś po prostu popatrzeć, jak robią to inne biblioteki javascript, takie jak prototyp jQuery oder itd. – Ridcully
Sprawdź wzór modułu: http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Dthth – edigu
Czy można poprawnie używać 'var lib = new function() {/ * blah blah * /} '? – Pithikos