4. Globals & Locals
• only function scope
• no block scope (ok, this is not exactly
true...)
• never, ever without var
Thursday, June 9, 2011
5. Globals & Locals
var a = 5;
(function() {
var a = 7;
})();
console.log(a) // 5
Thursday, June 9, 2011
6. Globals & Locals
var a = 5;
(function() {
a = 7;
})();
console.log(a) // 7
Thursday, June 9, 2011
7. Globals & Locals
• watch out for loops
for(var i = 0; i < 3; i++) {
// be sure you're not making i global!
}
Thursday, June 9, 2011
8. var & let
• let - variable with block scope
• implemented in JS 1.7 (part of ECMA6)
• sweet but not yet there
Thursday, June 9, 2011
9. var & let
<script type="application/
javascript;version=1.7">
var a = 6;
if(true) {
var b = 7;
}
console.log(a); // 6
console.log(b); // 7
</script>
Thursday, June 9, 2011
10. var & let
<script type="application/
javascript;version=1.7">
var a = 6;
if(true) {
let b = 7;
}
console.log(a); // 6
console.log(b); // Error: b is not defined
</script>
Thursday, June 9, 2011
11. module pattern
• extremely useful in apps that have more
than one JS file
• easy way to encapsulate and limit the
amount of global variables
• use please :)
• JavaScript Module Pattern: In-Depth - by
Ben Cherry http://bit.ly/j4vhTi
Thursday, June 9, 2011
12. module pattern
(function(){
// om nom nom, do stuff, nothing gets out of here
})()
var MyApp = function() {
// do stuff and return some object for future use
return {
om : 'nom'
}
} ();
MyApp.om // nom
Thursday, June 9, 2011
13. module pattern
var MyApp = function() {
var privateVariable;
function privateFunction(someVar) {
// mess around with privateVariable and someVar
}
var thisWillBePublic = function(someVar) {
return privateFunction(someVar)
}
return {
myAppMethod: thisWillBePublic
}
} ();
MyApp.myAppMethod();
Thursday, June 9, 2011
14. variable types
• undefined - variable that has no value assigned
• null - object with no value
• boolean - true or false
• string - 'this' "and that"
• number - double precision 64bit number & NaN
• object - everything else (yes, arrays and
functions too)
Thursday, June 9, 2011
15. Dynamic Typing
• Data types can change
var foo = 42;
foo = "Blah";
• „+” can convert to number
+"42" // 42
• „+” can convert to string
33 + " oops" // "33 oops"
"37" - 7 // 30
"37" + 7 // "377"
• Don’t kill the compiler - avoid changing types!
Thursday, June 9, 2011
18. Literals vs Built-in
Objects
var a = 1;
typeof a; // "number"
a instanceof Number; // false
a instanceof Object; // false
var b = new Number(1);
typeof b; // "object"
b instanceof Number; // true
b instanceof Object; // true
a == b // true
a === b // false
Same happens with strings & booleans
Thursday, June 9, 2011
19. Literals vs Built-in
Objects
var a = [];
typeof a; // "object"
a instanceof Array; // true
a instanceof Object; // true
var b = new Array(1);
typeof b; // "object"
b instanceof Array; // true
b instanceof Object // true
a == b // false - comparing references, not values!
a === b // false - same case
With arrays, objects and functions it works both ways
Thursday, June 9, 2011
20. Built-in Objects
• Object • RegExp
• Function • Error
• Array • ...
• String
• Boolean
• Date
Thursday, June 9, 2011
27. Objects
• almost everything is an object:
• functions, arrays, object literals, constructor instances..
• everything that is not a string, number, boolean
(literals!), null or undefined
• objects are always passed by reference (no clone method)
• comparing objects compares references (no equal
method)
• objects are dynamic - can be modified after creating
• they can inherit from each other
Thursday, June 9, 2011
28. Objects
var a = { b : 'om' }, a1 = { b : 'om' }
var c = a;
a === a1 // false
c === a // true
a.b // 'om'
c.b // 'om'
c.b = 'nom'
a.b // 'nom'
(function(obj) {
obj.d = 'ninja!'
})(a)
c.d // ninja!
Thursday, June 9, 2011
29. Objects
var obj = {key1 : 5}
obj.key1 // 5
obj['key1']; // 5
var a = 'key1';
obj[a] // 5
obj.someKey // undefined
obj.someKey.value // error
Thursday, June 9, 2011
31. Arrays
• Indexes are converted to strings and used as
names for retrieving values.
• Very efficient for sparse arrays.
• length is not actual size of array but highest
index + 1
• typeof [] returns ”object”
• Arrays can be augmented (as any other object)
Thursday, June 9, 2011
33. Arrays - deleting
elements
var arr = [1, 2, 3] // [1, 2, 3]
delete arr[1] // [1, undefined, 3]
var arr = [1, 2, 3] // [1, 2, 3]
arr.splice(1, 1) // [1, 3]
Thursday, June 9, 2011
34. Arrays - iterating
• Use for or while loop
• ECMA5 has more methods for iteration like
forEach
• for...in is dangerous and (usually) ineffective as
it uses not only array elements but also object
properties
• for..in can be effective in case of sparse arrays
but has to be used with hasOwnProperty method
Thursday, June 9, 2011
35. Arrays - iterating
Array.prototype.myArrMethod = function() { return 'thisIsMyArrMethod' }
var arr = [];
arr[3] = 3;
arr[1000] = 1000;
for(var i = 0, len = arr.length; i < len; i++){
console.log(arr[i])
}
// 3 x undefined, 3, 996 x undefined, 1000
for(var i in arr) {
console.log(arr[i])
}
// 3, 1000, function () { return 'thisIsMyArrMethod' }
for(var i in arr) {
if(arr.hasOwnProperty(i)) {
console.log(arr[i])
}
}
// 3, 1000
Thursday, June 9, 2011
37. Functions
• Functions are first class objects – can be passed,
returned or stored
• typeof function(){} returns ”function”
• In JS function is what in other languages is called
lambda
• Functions can be defined inside each other
• Functions return undefined if not set differently
(unless new operator is used)
Thursday, June 9, 2011
38. Functions - defining
function foo() {}
• is equivalent of:
var foo = function() {}
• Functions can be defined and called right away:
var foo = function(){}()
(function(a){})(123)
Thursday, June 9, 2011
39. Functions - closures
Function keeps a reference to its private variables
even after it has returned
function setPuppyBasket(initialPuppy) {
var basket = [initialPuppy]
return function(puppy) {
if(puppy) {
basket.push(puppy)
}
return basket.toString();
}
}
var puppyBasket = setPuppyBasket('black');
puppyBasket(); // 'black'
puppyBasket('white') // 'black,white'
puppyBasket('white') // 'black,white,white'
Thursday, June 9, 2011
40. Function - closures
• Allow to use private variables and methods
• Can cause problems when not used with
caution
• Excessive use of closures can affect script
performance - all objects are kept in
memory
Thursday, June 9, 2011
41. <p id="help">Helpful notes will appear here</p>
<p>E-mail: <input type="text" id="email" name="email"></p>
<p>Name: <input type="text" id="name" name="name"></p>
<p>Age: <input type="text" id="age" name="age"></p>
function showHelp(help) {
document.getElementById('help').innerHTML = help;
}
function setupHelp() {
var helpText = [
{'id': 'email', 'help': 'Your e-mail address'},
{'id': 'name', 'help': 'Your full name'},
{'id': 'age', 'help': 'Your age (you must be over 16)'}
];
for (var i = 0; i < helpText.length; i++) {
var item = helpText[i];
document.getElementById(item.id).onfocus = function() {
showHelp(item.help);
}
}
}
Thursday, June 9, 2011
42. for (var i = 0; i < helpText.length; i++) {
var item = helpText[i];
var elem = document.getElementById(item.id);
elem.onfocus = function() {
showHelp(item.help);
}
}
for (var i = 0; i < helpText.length; i++) {
var item = helpText[i];
var elem = document.getElementById(item.id);
elem.onfocus = function(helpItem) {
return function() {
showHelp(helpItem);
}
}(item.help)
}
}
Thursday, June 9, 2011
43. Functions - arguments
• special ‘array like’ object accessible inside
every function
• contains all arguments with which function
was invoked
• has length property but no other array
methods like splice or sort
Thursday, June 9, 2011
44. Functions - arguments
function joiner(separator) {
// make real array from arguments
var args = [].splice.call(arguments, 1)
return args.join(separator)
}
function joiner(separator) {
var len = arguments.length;
var joined = '';
for(var i = 1; i < len; i++) {
joined += arguments[i]
if(arguments[i+1]) {
joined += separator;
}
}
return joined;
}
joiner(':', 1, 2, 3); // 1:2:3
Thursday, June 9, 2011
45. Functions - length
• fnName.length - number of parameters function
expects
• arguments.length - number of parameters
actually passed to the function
function joiner(separator) {
console.log('joiner.length: ' + joiner.length)
console.log('arguments.length: ' + arguments.length)
}
joiner(':', 1, 2, 3);
// joiner.length: 1
// arguments.length: 4
Thursday, June 9, 2011
46. Function - invocation
• Function form
functionObject(arguments)
• Method form
thisObject.methodName(arguments)
thisObject["methodName"](arguments)
• Constructor form
new functionObject(arguments)
• Apply/call form
functionObject.apply(thisObj,[arguments])
Thursday, June 9, 2011
47. Functions - this
• this is an extra parameter. Its value depends on the
calling form.
• It’s the context in which function is called
• this gives methods access to their objects
• this is bound at invocation time
• Treat it like something that will be changing
• More information on this and context
http://j.mp/jFFgUB
Thursday, June 9, 2011
48. Function - invocation in
function form
functionObject(arguments)
• When a function is called in the function form, this is set
to the global object (always!)
• Most common usage but not very useful one
• It makes it harder to write helper functions within a method
because the helper function does not get access to the outer
this.
var that = this;
Thursday, June 9, 2011
49. Example
function oohLaLa() {
alert(this == window)
}
oohLaLa(); // true
Thursday, June 9, 2011
50. Function - method
form
myObject.methodName(args)
myObject["methodName"](args)
• When a function is called in the method form, this is
set to myObject - the object containing the function.
• This allows methods to have a reference to the parent
object
Thursday, June 9, 2011
51. Example
var ooh = {
laLa: function() {
alert(this === ooh)
}
}
ooh.laLa(); // true
var domNode = document.getElementById('elem');
domNode.onclick = ooh.laLa; // false - context is domNode!
var domNode = document.getElementById('elem');
domNode.onclick = function() {
ooh.laLa(); // true - context is ooh object
}
Thursday, June 9, 2011
52. Function - constructor
new functionObject(args)
• When a function is called with the new
operator, a new object is created and
assigned to this.
• If there is not an explicit return value, then
this will be returned.
Thursday, June 9, 2011
53. Example
var Ooh = function() {}
Ooh.prototype.laLa = function(obj) {
alert(this === obj)
}
var myOoh = new Ooh(); // myOoh is created,
// set to this and returned
myOoh.laLa(myOoh); // true
Thursday, June 9, 2011
54. Function apply/call
fnObject.apply(thisObj,[arg1, arg2])
fnObject.call(thisObj, arg1, arg2)
• this is set explicitely
Thursday, June 9, 2011
55. Function - bind
fnObject.bind(thisObj, arg1, arg2)
• Available in ECMA5
• Binding this object & presetting the
arguments
• Calling bind returns new - curried -
Thursday, June 9, 2011
56. Example
function sum() {
var sum = 0;
for(var i = 0; i < arguments.length; i++) {
sum += arguments[i]
}
return sum
}
var addToOne = sum.bind(null, 1);
addToOne(2) // this === null, returns 3
var addToThree = sum.bind(null, 1, 2);
addToThree(3) // this === null, returns 6
Thursday, June 9, 2011
57. To be (hopefully)
continued with
event loop,
inheritance
&
other JS sweetness
Thursday, June 9, 2011