グローバル名前空間が乱雑にならないように、次のような構造を使用します。
var MyLib = {
vars: {
var1: 'value1',
var2: 'value2'
},
func1: function () {
return this.vars.var1;
},
func2: function () {
alert("This is func2");
}
};
MyLib.func1();
MyLib.func2();
すべての変数を独自のサブオブジェクトに配置したことに気付くでしょう。これは、読みやすく、開発しやすいようにするためだけに行われます。
編集1:
これが私が使用する別の方法です
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() );
この構造体はJSクロージャとコンストラクター関数を利用しているため、プライベート変数をプライベートに保つのは簡単です。
編集2:
さらに、コンストラクターを返さない別のクロージャー設定も使用しました(例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 : {}));
そしてそれが実際に動作するのを見るには:
myLib('something').set('made public, outside of the closure by the `get` method');
myLib('something').get(function(a){
console.log(a);
});
myLib
また、実行されている場所と含まれている方法を考慮して、私が公開している方法も確認してください。
編集3(2017年7月):
module
フルスタック(w / Node.js)JavaScriptエンジニアとして、そしてBrowserifyの登場として、マルチファイル(分離された、より小さな)をコンパイルするためのビルドシステムとしてGulpまたはGruntのいずれかを利用するNodejsスタイルのパターンの使用を強くお勧めしますコードのビット)を1つのライブラリに。
このモデルは、より機能的なアプローチを促進するのに役立ち、開発者がライブラリ内のより一般的な機能を個別のファイルに抽象化できるようにし、開発をはるかに容易にします。
ああ、ES6を使って!
// file: src/divideIntByFour.js
const divideIntByFour = (int) => {
return int / 4;
};
module.exports = divideIntByFour;
...簡略化された例として