Javascript Basics - part 1
-
Upload
kasia-drzyzga -
Category
Documents
-
view
3.982 -
download
1
description
Transcript of Javascript Basics - part 1
JS - Basicspart 1
Thursday, June 9, 2011
JS - overview• JavaScript =/= DOM
• Dynamic language
• Loosely & dynamically typed
• Functional language
• Almost everything is an object
• Prototypal inheritance (objects not classes)
• Closures (lambda)
• Event loop
• ECMA5
• SSJS
Thursday, June 9, 2011
Variables
Thursday, June 9, 2011
Globals & Locals
• only function scope
• no block scope (ok, this is not exactly true...)
• never, ever without var
Thursday, June 9, 2011
Globals & Locals
var a = 5;
(function() { var a = 7;})();
console.log(a) // 5
Thursday, June 9, 2011
Globals & Locals
var a = 5;
(function() { a = 7;})();
console.log(a) // 7
Thursday, June 9, 2011
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
var & let
• let - variable with block scope
• implemented in JS 1.7 (part of ECMA6)
• sweet but not yet there
Thursday, June 9, 2011
var & let<script type="application/javascript;version=1.7">
var a = 6;if(true) { var b = 7; }console.log(a); // 6console.log(b); // 7
</script>
Thursday, June 9, 2011
var & let<script type="application/javascript;version=1.7">
var a = 6;if(true) { let b = 7;}console.log(a); // 6console.log(b); // Error: b is not defined
</script>
Thursday, June 9, 2011
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
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
module patternvar 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
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
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
Falsy Values
• undefined
• null
• false
• NaN, 0 (both are numbers)
• "" '' (empty strings)
!null; !undefined; !0; !''; !false; !NaN // true
Thursday, June 9, 2011
Falsy Values
0 == ''; 0 == false; '' == false // true
0 == undefined; 0 == null // false
undefined == null // true
NaN == NaN // false
Thursday, June 9, 2011
Literals vs Built-in Objects
var a = 1;typeof a; // "number"a instanceof Number; // falsea instanceof Object; // false
var b = new Number(1);typeof b; // "object"b instanceof Number; // trueb instanceof Object; // true
a == b // truea === b // false
Same happens with strings & booleans
Thursday, June 9, 2011
Literals vs Built-in Objects
var a = [];typeof a; // "object"a instanceof Array; // truea instanceof Object; // true
var b = new Array(1);typeof b; // "object"b instanceof Array; // trueb 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
Built-in Objects• Object
• Function
• Array
• String
• Boolean
• Date
• RegExp
• Error
• ...
Thursday, June 9, 2011
Operators
Thursday, June 9, 2011
Operators || and &&
function a(b){ return b || 7;}
a(); // 7a(9); // 9a([]); // []a(0); // 7
function a(b){ return b && 7;}
a(); // undefineda(9); // 7a([]); // 7a(0); // 0
Thursday, June 9, 2011
Operator !!
• makes a boolean out of anything:
!!0 !!'' !!null !!undefined !!NaN // false
!!5 !!'om nom nom' // true
!![] !!{} // true
!!function(){} // true
Thursday, June 9, 2011
Operators ~~ and |
• get integer from any number (fastest way)~~3.75
0 | 3.75
parseInt(3.75)
Thursday, June 9, 2011
== && ===
• == checks only the value
• === checks also the type
• always use ===
[] == ![] // true
[] === ![] // false
Thursday, June 9, 2011
Objects
Thursday, June 9, 2011
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
Objectsvar a = { b : 'om' }, a1 = { b : 'om' }var c = a;
a === a1 // falsec === 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
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
Objects - creatingvar obj = { key1 : ”value”, key2 : 7, key3 : true, key4 : {}, key5 : [], key6: function(){}, key7: myFun}function myFun() {}
var obj = {};obj.key1 = 'str'; obj.key2 = 7; obj.key3 = {}; obj.key3.boo = function() {}
Thursday, June 9, 2011
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
Arrays - length property
var arr = [];
arr[3] = 1;
arr.length // 4
arr // [undefined, undefined, undefined, 1]
Thursday, June 9, 2011
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
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
Arrays - iteratingArray.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
Functions
Thursday, June 9, 2011
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
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
Functions - closuresFunction keeps a reference to its private variables even after it has returnedfunction 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
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
<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
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
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
Functions - argumentsfunction 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
Functions - length• fnName.length - number of parameters function
expects
• arguments.length - number of parameters actually passed to the functionfunction 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
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
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
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
Example
function oohLaLa() { alert(this == window) }oohLaLa(); // true
Thursday, June 9, 2011
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
Examplevar 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
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
Example
var Ooh = function() {}Ooh.prototype.laLa = function(obj) { alert(this === obj)}
var myOoh = new Ooh(); // myOoh is created, // set to this and returnedmyOoh.laLa(myOoh); // true
Thursday, June 9, 2011
Function apply/call
fnObject.apply(thisObj,[arg1, arg2])
fnObject.call(thisObj, arg1, arg2)
• this is set explicitely
Thursday, June 9, 2011
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
Examplefunction 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
To be (hopefully) continued with
event loop,inheritance
& other JS sweetness
Thursday, June 9, 2011