javascript - uni-weimar.de filejavascript philipp seltmann & clement welsch sommer 2016....
TRANSCRIPT
JavaScript
Philipp Seltmann & Clement Welsch
Sommer 2016
Characteristics
– functional
– object oriented
– dynamic type system
– prototypal inheritance
Functional Programminga very brief introduction
Key Concept #1
Functions are first class citizens – can be passed around as argument or return value → functions and data are the same
– can be composed → functions are the building blocks
Key Concept #2
Data-in/Data-out – Functions transform data by taking values as
arguments an producing result values → streaming
– No loops, only recursion to get rid of iteration
variables → favor of immutable state
class ExampleProgram {
private static int i = 0;
public static int inc() { i = i + 1; return i; }
public static void main(String args[]) { System.out.println( inc() ); // 1 System.out.println( inc() ); // 2 } }
Side Effects
Side Effects
– A function or expression is said to have a side effect
(Nebeneffekt), if it changes some state somewhere
– Purely functional programming languages offer only
immutable fields (Values) and no mutable fields
(Variables) → Hence, they are free of side effects
– A program, free of side effects, is free of deadlocks
and race conditions
Idempotencyclass ExampleProgram {
private static int i = 0;
public static int set(final int x) { i = x; return x; }
public static void main(String args[]) { System.out.println( set(2) ); // 2 System.out.println( set(2) ); // 2 } }
Idempotency– The result of an idempotent
function remains the same, no
matter how often the function is
applied (for the same arguments).
– Idempotent functions can cause
side effects
execi(f(x)) = execi+1(f(x)) ∀i
Idempotence (cs)
Idempotence (math)
f(f(x)) = f(x)
execi(f(x)) ≠ execi+1(f(x)) ∃i
Non-idempotent (cs)
Pure Functionsclass ExampleProgram {
private static int i = 0; public static int add(final int x, final int y) { return x + y; }
public static void main(String args[]) { System.out.println( add(1,2) ); // 3 System.out.println( add(1,2) ); // 3 } }
– A function or expression is called pure (rein) or
referentially transparent, if it is idempotent and has no
side effects
– Therefore the expression can be substituted by its
evaluated value → functions and data are the same
– Functional Programming supports being pure or a
least idempotent
Pure Functions
JavaScripta few advanced concepts
Functions
function name(argumentlist) block
var name = function(argumentlist) block ;≙
Named functions
Anonymous functions
function(argumentlist) block
Functions
– In a functional programming language
functions are first class citizens
– The two notations for named functions
are equivalent
– Blocks are denoted by { }
– Anonymous functions have nothing to
do with closures
Higher Order Functions[1,2,3,4,5].map(function(val) { return val*val; }); //returns [1,4,9,16,25]
[1,2,3,4,5].reduce(function(prev,val) { return prev+val; }); //returns 15
[1,2,3,4,5].map((v) => v*v).reduce((p,v) => p+v); //returns 55
Higher Order Functions
– Higher order functions are functions
that take another function as parameter
– Common examples are map, reduce,
filter, forEach, …which work on
sequences and apply a function, given
as parameter, to all elements of the
sequence
Closuresfunction foo() { var x=0; function increment() { x = x + 1; return x; } return increment; }
var y = foo(); var z = foo(); y(); //returns 1 y(); //returns 2 y(); //returns 3 z(); //returns 1
function foo(x) { return function() { x = x + 1; return x; } }
var y = foo(0); var z = foo(3); y(); //returns 1 y(); //returns 2 z(); //returns 4 z(); //returns 5
Closures
– Closures conserving context
– They simulate inner state (side effects)
in the functional world
– increment() is an inner function
– y is the closure that catches x via foo()
– z is another closure with its own local x
Objects
function MyConstructor() { var self = this; ... }
var myObject = new MyConstructor();
var myObject = { member: value, field:[wert1, wert2, wert3], obj: {...}, method: function() {...} };
Constructor objects Literal objects
– Constructor objects are instantiated by calling a
constructor function with new
– Object literals define a single instance in place
– Objects and HashMaps are the same in JavaScript
– Variables and this have function scope, not block scope
– The self construction grants inner functions
access to public members of the object
Objects
Membershipfunction MyObject(...) { // private definitions var that = this; var membername = value; function membername(...) {...}
// privileged definitions this.membername = function (...) {...};
// public definitions this.membername = value; }
// public definitions in the prototype MyObject.prototype.membername = value; MyObject.prototype.membername = function (...) {...};
Membership– Private membership can only be realized via
constructor objects
– All members of an object literal are public
– Definitions in the prototype are available to all
instances of the object
– The value of a variable in the prototype is shared
between all instances
JSON
var myObject = { key: 'value', array:[8, 16, 32], object: {...}, method: function() {...} };
{ "key": "value", "array":[8, 16, 32], "object": {...}, method: function() {...} }
JSON.stringify()
JSON.parse()
Object literal JavaScript Object Notation
JSON– JavaScript Object Notation (JSON) is kind of a
subset of the object literal syntax
– Two major differences
– All keys must be strings
– No functions are allowed
– Never use eval() to instantiate JSON, it’s evil!
– Since EMCA-Script 5 the JSON.parse() and
JSON.stringify() methods do the job
Non Blocking
setTimeout(function() { console.log('World!'); }, 1000); console.log('Hello, ');
Non Blocking– JavaScript code runs in a non blocking fashion
– Thus, asynchronously called functions do not
intercept further execution of the program
– The output of the example will be „Hello, World!“
– The last line does not wait for the callback to
become executed, but will print immediately and
the callback prints when invoked after one second
Error Handlingvar divide = function(x, y, callback) { if (y === 0) { return callback(new Error('Can not divide by zero')); } return callback(null, x/y); };
divide(4, 2, function(err, result){ if (err) { console.log(err); return; } console.log('4/2=' + result); });
Error Handling– Do not use throw nor try…catch in JavaScript
– The first parameter of the callback function should
be the error object
– The callback should be passed as the last
parameter of the called asynchronous function
– The if-Statements in this example are called
Guard Statements
– Guard Statements must be finalized with a return
to ensure the abortion of the function
ServerWebservice
Model
Client
JavaScript Controller
Static Fileserver
HTML + CSS
«http»1..n
1
XML(ATOM)
static files
«bind»
View
Controller
Further Reading
JavaScript – Douglas Crockford
– Survey of JavaScript
– Code Conventions
– Membership in JavaScript
– JSON
– Eloquent JavaScript
– JavaScript Design Patterns
– Heise: JavaScript
– Heise: OO in JavaScript
Podcasts – CRE146: Javascript
– CRE167: node.js
Videos – Ruby + JS WAT?