var application = {
name: "Christoph's Application",
};
application.moduleOne = {
name: "Tom's Module",
provideAppInfo: function () {
return
this.name + " is part of "
+ application.name + "!";
}
};
application.moduleOne.provideAppInfo(); // Tom's Module is part of Christoph's Application!
Scopes
– Function block scopes
– Enclosing block scopes
– Scope chain
– Local scopes
– Scope overloading
Function block scopes vs. enclosing block scopes
Make let not var
function functionBlockScope() {
let foo = 'bar';
// function block scoped
var bar = 'foo';
// function block scoped
}
function functionBlockScope() {
for (var i = 0; i < 5; i++) {
// i is visible to
// the whole function
}
//i *is* visible out here
}
function enclosingBlockScope() {
for (let i = 0; i < 5; i++) {
//i is only visible in here
//(and in the for() parentheses)
//and there is a separate
//i variable for each
//iteration of the loop!
}
//i *is not* visible out here
}
let and var
Redeclaration of variables
'use strict';
var me = 'foo';
var me = 'bar';
// No problem, 'me' is replaced.
'use strict';
let me = 'foo';
let me = 'bar';
// SyntaxError:
// Identifier 'me' has
// already been declared
var foo = 'bar';
// globally scoped
let bar = 'foo';
// globally scoped
console.log(window.foo);
// 'bar'
console.log(window.bar);
// undefined
Scope chain
Access to all variables within the function and to all of its parents!
let globalVar = 1; let outer = function () { let outerVar = 2 let inner = function () { let innerVar = 3; let core = function () { let coreVar = 4; return coreVar + innerVar + outerVar + globalVar; };
return core(); };
return inner(); };
outer(); // Result: 10
Local scope
The local scope always wins
Scope overloading
Scope overloading
Closures
Closures
– A function embraced by another function
– Used for data encapsulation
– Access by reference
Don't forget:
– A function can be the return value of another function
var application = function () {
var name = "Jörg's Application";
var version = "v0.0.1";
var init = function () {
var msg = "Successfully launched: ";
return msg + name + ", " + version;
};
var name = "Werner's Application";
var version = "v0.2.0";
return {
getVersion: function () { global.alert(
"Version " + version
);
}
};
}(window));
var application = (function (window, $) {
var name = "Lisa's Application";
return {
changeContent: function () { $(".my-container").html(
"New content"
); window.alert(
"The content has changed!"
);
}
};
}(window, jQuery));
Module export
// Expose module as global variable
var Module = function(){ // Inner logic
function sayHello(){
console.log('Hello');
} // Expose API
return {
sayHello: sayHello
} }
var module = new Module();
module.sayHello(); // Hello