🚀🔥🚀
(function() {
// this is a scope
})();
function util() {
// this is a scope
}
var util = function() {
// this is a scope
}
var global = 'Global scope';
// or
window.global = 'Global scope';
(function() {
var local = 'Local scope';
})();
function simpleFunction() {
var local = 'Local scope';
}
var globalVar = 'Global Variable';
(function() {
console.log('globalVar: ', globalVar);
var localVar = 'Local scope';
})();
console.log('localVar: ', localVar);
console.log('globalVar: ', globalVar);
var globalVar = 'Global Variable';
(function() {
console.log('globalVar: ', globalVar);
var localVar = 'Local scope';
})();
console.log('localVar: ', localVar); // undefined
console.log('globalVar: ', globalVar); // 'Global Variable'
// Uncaught ReferenceError: localVar is not defined
var globalVar = 'Global Variable';
(function() {
var localVar = 'Local scope';
(function() {
var childVar = 'Child scope';
console.log('childVar: ', childVar); // 'Child scope'
console.log('localVar: ', localVar); // 'Local scope'
console.log('globalVar: ', globalVar); // 'Global Variable'
})();
console.log('childVar: ', childVar); // undefined
console.log('localVar: ', localVar); // 'Local scope'
console.log('globalVar: ', globalVar); // 'Global Variable'
})();
console.log('childVar: ', childVar); // undefined
console.log('localVar: ', localVar); // undefined
console.log('globalVar: ', globalVar); // 'Global Variable'
var Module = (function () {
// code
})();
var Module = (function () {
var _privateMethod = function() {
// Private method
}
return {
publicMethod: function() {
// Public method
}
}
})();
var Module = (function () {
var _privateMethod = function() {
// Private method
}
})();
Module._privateMethod(); // undefined
var Module = (function () {
// ... methods
return {
publicMethod: function() {
// Public method
return 'JavaScript Module Pattern';
}
}
})();
Module.publicMethod(); // 'JavaScript Module Pattern'
var Module = (function () {
var _privateMethod = function() {
// Private method
return 'JavaScript Module Pattern';
}
return {
publicMethod: function() {
// Public method
return _privateMethod();
}
}
})();
Module.publicMethod(); // 'JavaScript Module Pattern'
var Module = (function () {
var localObject = {};
var _privateMethod = function() {
// Private method
}
localObject.publicMethod = function() {
// Public method
}
return localObject;
})();
var Module = (function () {
var methodOne = function() {
}
var methodTwo = function() {
}
return {
publicMethodOne: methodOne,
publicMethodTwo: methodTwo
}
})();
var Module = (function () {
var localObject = {};
var _privateMethod = function() {
// Private method
}
localObject.publicMethod = function() {
// Public method
}
return localObject;
})();
var Module2 = (function (Module) {
var localObject = {};
var _privateMethod = function() {
// Private method
Module._privateMethod();
}
localObject.publicMethod = function() {
// Public method
}
return localObject;
})(Module);