JavaScriptas a
dynamic,functional
language
Door:
Jan Sabbe &
Wouter Groeneveld
Inhoud
1. Context2. Primitives & objecten3. Prototypal inheritance4. Functies & closures5. Scoping & contexting6. Pitfalls
Hoe JS gebruikt wordt
<script>
function oei() {
doStuff();
i = 10;
copyPasta(this.i, 20);
}
function copypasta(i, j) {
alert(new Date(i).getTime());
return j;
}
</script>
<a onclick=“oei();”>lala</a>
Hoe JS gebruikt kan worden
<script>
$(document).ready(function() {
$(“#link”).click(MyStuff.oei);
});
var MyStuff = (function() {
function privateStuff() { ... }
return {
oei: function() {
...
}
};
})();
</script>
<a id=“link”>lala</a>
Primitives & objecten
Variable declaration
var variabele = 5;
var hallo = "hallo";
var 1 = “een”; // syntax error
var _ = “omgh4x”; // ok
Primitives
number
string
boolean
Immutable & case sensitive!
Speciale values
undefined: onbekende waardevar a;
a == undefined;
null: lege waardevar a = null;
a == null;
NaN: geen getalisNaN(parseInt(“bomma”)) == true
isNaN(undefined)== ??
Infinity: groter dan alle andere numbers1 / 0 == Infinity
typeof = keyword
geeft strings:
“object” (ook bij null)
“function” (ook al is een functie een object)“string”, “boolean”
“number” (ook bij Infinity, NaN)
“undefined”
String utility functions
str.split
str.indexOf
str.replace(regex)
str.toLowerCase
...
Zie API:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String
Objecten:
een map van key - values
value kan getal, string, object, functie zijn
manieren om aan te maken
literal
new Object()
var locatie = {
x: 3,
y: 4,
afstandTot: function () {
var dx = this.x + this.y;
return Math.sqrt(dx);
}
}
var locatie = new Object();
locatie.x = 3;
locatie.y = 4;
locatie.afstandTot = function () { … };
manieren om aan te maken
Literal objects syntax – opletten!!
dit wel:
var obj = {
key1: value1,
key2: value2,
key3: value3
};
dit niet:
var obj = {
var bla = 3;doeStuff();
};
lezen
wijzigen
toevoegen
verwijderen
console.log(locatie.x);
console.log(locatie[„x‟];
itereren
locatie.z = 1;
locatie[„z‟] = 1;
for (var key in locatie) {
console.log(locatie[key]);
}
delete locatie.z;
delete locatie[„zumba‟];
locatie.x = 43;
locatie[„x‟] = 43;
Functiesfunction eenFunctie(naam) {
console.log("Hello, " + naam);
}
Functie literals:
var eenFunctie = function(naam) {
console.log("Hello, " + naam);
}
Gevolg: géén overloading, slechts def. overschrijven
voorbeeld:
functie kan object retourneren
function createPunt(x,y) {
return {
x: x,
y: y,
afstandTot: function (anderPunt) {
return Math.sqrt(...);
}
};
}
Arrays: (= een object)var arr = ["a", "b", "c"];
Itereren:x.forEach(function(i) {
console.log(i);
});
for(var i = 0; i < ...)
Array utility functions
arr.length
arr.push, pop
arr.splice, slice
arr.shift, unshift
arr.sort
arr.filter, arr.map
...
Zie API:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array
Associative Arrays => Objects
var objArr = {
0: "nul",
1: "een"
};
var arr = [ "nul", "een" ];
Lab 1
prototypes
object verwijst naar ander object (prototype)
locatie
myObject
opzoeken van property
altijd eerst in object
zelf opzoeken
locatie
myObject
opzoeken van property
locatie.x
locatie
myObject
indien niets gevonden,
zoeken in prototype
opzoeken van property
locatie
myObject
opzoeken van property
locatie.y
locatie
myObject
opzoeken van property
eventueel verder zoeken
locatie
myObject
anotherObj
opzoeken van property
locatie.w
locatie
myObject
anotherObj
wijzigingen
altijd in object zelf
locatie
myObject
wijzigingen
locatie.x = 4;
locatie
myObject
toevoegen
locatie.y = 3;
locatie
myObject
verwijderen
delete locatie.y
locatie
myObject
Object.create (ES5)
var punt = {
afstandTot: function(anderPunt) {
return Math.sqrt(...);
}
};
var punt1 = Object.create(punt);
punt1.x = 3;
punt1.y = 4;
var punt2 = Object.create(punt);
ECMAScript ?
ECMA= European Computer Manufacturers Association
= standaardisatie (de “spec”)
Browsers implementeren ECv5 = Javascript
2 objecten, 1 prototype ??
var proto = {
wow: “wow man da‟s vet!”
};
var obj = Object.create(proto);
var obj2 = Object.create(proto);
console.log(obj.wow == obj2.wow);
console.log(obj.wow);
proto.wow = “mind is blown, again...”;
console.log(obj.wow);
prototype is een object
kan dus steeds gewijzigd worden
wordt bijvoorbeeld gebruikt door es5-shim
om standaard API te implementeren op IE
Array.prototype.telEersteTweeOp = function () {
return this[0] + this[1];
}
[1,2].telEersteTweeOp();
Lab 2
Function arguments magic:
function wow() {
console.log(arguments[1]);
}
wow("jos", "lowie"); // prints "lowie"
closure:"een functie die de omgeving waarin hij is aangemaakt bijhoudt"
functieX(7)
functieY()
functieX()
functieY(3)
functieY(4)
Functie evaluatie = nieuwe omgeving!
var omgevingY = functieX();
omgevingY(3);
omgevingY(4); // arr = [3, 4]
functieX()(10);
// nieuwe arr = [10]
// vorige arr = [3, 4]
hoisting
var a = 3;
function f() {
console.log(a);
var a = 5;
}
f(); // wat is de uitkomst?
Best practice: definieer alle vars eerst:
function a() {
var a, b, c, ...;
...
a = 5;
}
JSLint checkt hierop.
Lab 3
Scope chaining: toplevel scope = window!
w = 6; // same as „window.w = 6;‟
// same as „var w = 6;‟
function F() {
var X = 55;
var Z = 10;
function FinF(){
var X = 50;
var Y = 60;
}
}
Scope chaining
function test () {
var a = 5;
if(a === 5) {
var b = 555;
...
}
console.log(b); // kan dit?
}
function test () {
var a = 5, b;
if(a === 5) {
b = 555;
...
}
console.log(b);
}
... maar wél Function level scope:
JS heeft géén Block level scope:
best practice: vars begin van functie zetten
Functie definieren en direct evalueren:
(function(){})();
Interessant voor encapsulatie!
function test () {
var a = 5;
if(a === 5) {
(function () {
var b = 555;
})();
}
console.log(b);
}
Private variabelen voor object:
function createPersoon() {
var naam = 'Jos';
return {
getName: function() {
return naam;
}
};
}
var persoon = createPersoon();
persoon.getName(); // === “Jos”
persoon.naam // === undefined
Module pattern:
var MOD = (function(dep1, dep2) {
var mr = "Mr.";
function createPersoon(naam) {
return {
getName: function() {
return mr + naam;
}
};
}
return {
init: function() { ... },
createPersoon: createPersoon
};
})(dependency1, dependency2);
Wanneer moet ik een module maken?
• Duplicatie • Plugin, framework, ...• Reuse (component-gebaseerd)
Wanneer mag ik geen module maken?
• Eenmalige code, uniek op 1 pagina• Weinig code (gebruik gewoon encapsulatie)
Hou het zo simpel mogelijk!
Context in functions
function afstander(anderPunt) {
return this.x + this.y;
}
var punt1 = {
x: 1,
y: 1,
afstandTot: afstander
}
var punt2 = {
x: 2,
y: 2,
afstandTot: afstander
}
op wat slaat this?
afstander.apply(punt1, [punt2]);
afstander.call(punt1, punt2);
afstander(punt1)
punt1.afstandTot(punt2)
punt2.afstandTot(punt1)
this wordt bepaald bij oproepen functie
this = punt1
this = punt2
this = window (globale object in javascript)
this kan expliciet opgegeven worden
this = punt1
this = punt1
callbacks en contexting:
var persoon = {
naam: "jos",
roep: function() {
alert("ey, " + this.naam);
}
}
setTimeout(persoon.roep, 1000);
callbacks fix closures:
var persoon = {
naam: "jos",
roep: function() {
alert("ey, " + this.naam);
}
}
setTimeout(function() {
persoon.roep()
}, 1000);
callbacks fix binding:
var persoon = {
naam: "jos",
roep: function() {
alert("ey, " + this.naam);
}
}
setTimeout(
persoon.roep.bind(persoon), 1000);
Lab 4 + JSLint
new operator: constructor functies
var jos = new Persoon()
var jos = Object.create(Persoon.prototype);
Persoon.call(jos);
is hetzelfde als
new
function Persoon() {
this.naam = “jos”;
// no return statement
}
Persoon.prototype.praat = function () {...}
var jos = new Persoon();
jos.naam === “jos";
jos.praat();
new operator: constructor functies
var jos = new Persoon();
jos instanceof Persoon === true;
// is hetzelfde als:
Persoon.prototype.isPrototypeOf(jos)
instanceof
Pitfalls
== doet aan type-casting
== (equality operator) probeert te casten naar zelfde type
gebruik
=== (identity operator) en
!== - doen geen type casting
function ding(a) {
if(!a) a = 5;
return a;
}
ding(400); // ?
ding(0); // ?
ding(null); // ?
Expliciet checken:if (a === undefined)
Falsy values:
Objecten als key:
var obj = {};
var key1 = new Object();
var key2 = new Object();
obj[key1] = “hi”;
obj[key2] = “yo”;
console.log(obj[key1]); // ??
Oplossing: toString() implementeren?
=> Gebruik een framework
typecasting lolligheid
[] + 23 ?
false + 23 ?
true + 23 ?
null + 23 ?
[1, 2] + 23 ?
“kadootje” + 23?
undefined + 23 ?
Infinity + 23 ?
Conclusie
Hoe JS gebruikt werd!!!
<script>
function oei() {
doStuff();
i = 10;
copyPasta(this.i, 20);
}
function copypasta(i, j) {
alert(new Date(i).getTime());
return j;
}
</script>
<a onclick=“oei();”>lala</a>
Voor wie nog honger heeft
http://www.jefklak.be/wiki/code/javascript/home
Top Related