JavaScript - Programming Languages course
Transcript of JavaScript - Programming Languages course
2
A little bit about myself
Graduated from the CS faculty in 2001
Started to work in IBM research – Haifa about a year before that In the domains of visual programming
environments, end user development, cloud computing
Extensive usage of Java and JavaScript
Source: If applicable, describe source origin
3
JavaScript
The language of the web
Web applications Mobile applications
Dynamic language
Dynamic typing Dynamic binding No compilation till execution time
4
How would you summarize JavaScript in one sentence:
Everything is dynamic
Code simplification
Exactly what web apps developers need(because the web is a hostile platform, and the mobile web is even worse)
JavaScript
5
Type system
Prototypes and inheritance
Functions as first class citizens
Closures
Dynamic binding
What will we cover
6
JavaScript type system
7
Types
Number – a 64 bit (a.k.a double) No integer
String immutable No char
Boolean Objects
Array Function
Unit types null undefined NaN
8
Type system
Strongly typed (loose definition) With clear coercion rules
== , != a comparison without type coercion ===, !== a comparison with type coercion4 == ‘4’; //true4 === ‘4’ // false
The type of a variable can be determined using the ‘typeof’ operator
Dynamic typing The type is not declared
var a = 3; // number Changing the variable’s content changes its type
a = ‘s’; // string Type rules are enforced at runtime
9
Everything is a boolean
Strongly typed, but still…
Everything in JavaScript has its boolean interpretation Usually referred as ‘truthy’ and ‘falsy’
These values are interpreted as false when needed: 0, “”, null, undefined, NaN, false Everything else is true
What is it good for ?
10
Everything is a boolean – what is it good for?
Part of an ‘if’ statement All of the following statements are equivalent
If(a != null)If(a) If(a !== null && a !== undefined && a !== ‘’ && a !== 0 && a !== NaN && a !== false)
11
Everything is boolean – what is it good for?
Logical and (&&) Receives two operands If the first operand is truthy, then returns the second
operand’s value Otherwise returns the first one
Sometimes called the guard operator
var val;If(obj){ val = obj.methodCall();}else{ val = obj;}
var val = obj && obj.methodCall();
12
Everything is boolean – what is it good for?
Logical or (||) Receives two operands If the first operand is falsy, then returns the second
operand’s value Otherwise returns the first one
Sometimes called the default operator
var val;If(possibleVal){ val = possibleVal;}else{ val = defaultVal;}
var val = possibleVal || defaultVal;
13
Objects are objects
An object is a collection of things (fields) Data (members) Functions (methods)
A set of mappings between a name of a field (key) to the field (value), done using one of these ways:
anObject.fieldName = 3;anObject[“fieldName”] = 3;
(*)these lines are usually equivalent Just like a hashmap (without hash value and rehash)
The mapping can be changed in run-time It is possible to replace a method with another method
Still, there is a way to extend objects based on other objects (note - not classes)
14
I’ll have what she’s having – prototypal inheritance
15
The prototype
The prototype is an object Just like any other object Each object can act as a prototype
Each object has a prototype This is a hidden link
Created when the object is created Cannot be changed
The prototype itself can be changed Just like any other object
16
The prototype – when is it used?
Inheritance - using functionality declared elsewhere
On access to a field of an object WHEN this field is not part of that object The object’s prototype is accessed for that field And then the prototype’s prototype This goes all the way till the prototype of Object
A nice metaphor for it is that an object is a transparency placed on top of its prototype
17
name: “Jeff”
age: 32
job: “barber”
title: “Mr”
The prototype (pType)
The object (theObject)
theObject.age; // 32
pType.age ++;
name: “Jeff”
age: 33
job: “barber”
title: “Mr”
The object (theObject)
The prototype (pType)
theObject.age; // 33
delete theObject.age; // nothing happens
theObject.age; // 33
delete pType.age; // no more age field
theObject.age; // undefined
18
name: “Jeff”
age: 32
job: “barber”
title: “Mr”
The prototype (pType)
The object (theObject)
theObject.age; // 32
theObject.age ++; // value read from pType, added to theObject
name: “Jeff”
age: 32
job: “barber”
title: “Mr”
age: 33
The object (theObject)
The prototype (pType)
theObject.age; // 33
delete theObject.age; // no more age member in theObject
theObject.age; // 32
delete pType.age;
theObject.age; // undefined
19
Polymorphism
One of the most important attributes of OO languages
JavaScript’s objects are not rigid enough to provide single-morphism
There are JavaScript toolkits that add this functionality to the language The most renown for it is the “Dojo Toolkit”
20(From the tyranny of the compiler)
21
Functions
22
Functions are objects
Have members e.g., length (the number of arguments in the function’s
declaration) Have methods
E.g., toString (returns a string containing the function’s signature and body)
Are first class citizens Can be sent as arguments to a function Can be returned as a return value from a function
Can be executed
23
function add(a,b){
return a+b;
};
add.length;// 2
add.toString(); // “function add(a,b){return a+b;}”
Functions are objects
24
More about functions
Can be defined within another function
In that case the inner function knows of all the things defined within the outer function
This is called closure
What is it good for?
25
Write a function that calculates the fibonacci value of a number
26
Classic solution
function fib(n){
if(n < 2)
return n;
return fib(n-1) + fib(n-2)
}
fib(10) results in 177 calls to the fib function
27
Solution with closure
function fastFib(n){ var memo = [0,1]; var fib = function(n){ var result = memo[n]; if(result === undefined){ result = fib(n-1) +fib(n-2); memo[n] = result; } return result; } return fib(n); }fastFib(10) results in 19 calls to the fib function
This pattern is nicknamed memoization
28
Functions - what else is dynamic
Every time a function is executed it has a built in array-like variable called ‘arguments’ It holds the set of arguments sent in the function call arguments[i] is the i-th argument in the function call
This is needed since the function’s signature is just like road signs in Rome Recommendation only
It is valid to call the function with either more or less arguments then in its signature
29
Functions – arguments vs length
func.length > arguments.length The last (func.length - arguments.length) have
the value of undefined func.length < arguments.length
The last (arguments.length - func.length) are accessible only from the arguments variable
func.length == arguments.length No problem
30
Functions – what’s ‘this’
Every time a function is executed it has a built in variable called ‘this’
‘this’ points out to the context in which the function would run The context is bound to the function The binding is done in run-time
The binding is dependant upon the way the function was called There are 4 forms a function can be called
31
Function call forms
Method form
Function form
Apply form
Constructor form
32
The method form
The function is a field of an object
The call is written in the following way: theObject.FuncName();
The ‘this’ variable points out to theObject
33
The function form
The call is written in the following way: funcName();
The ‘this’ variable points out to the global object
This call form makes the usage of helper function within other function to be sometimes tricky
34
The apply form
Each function has a function called ‘apply’
Receives two arguments An object that would act as the ‘this’ variable
when the function is executed An Array that would act as the ‘arguments’
variable when the function is executed
The call is written in the following way: funcName.apply(thisPtr, [newArgs]);
35
The constructor form
Constructors are the only element in JavaScript that starts with capital letters Though this is just a convention
Used to create and initialize a specific object The ‘this’ variable points out to a newly created object
If the function has a field called ‘prototype’ then this field is the prototype of the created element
This call is written in the following way: var newMyObj = new MyObject();
36
Constructor form – an example
function AA (name, title) {
this.name = name;
this.title = title;
}
AA.prototype = {‘height’:3};
var a = new AA(“John”, “Mr”);
function AA (name, title) {
this = {};
this.linkToPrototype = AA.prototype || Object.prototype;
this.name = name;
this.title = title;
return this;
}
a.name;// “John”
a.title; // “Mr”
a.height;// 3
The code Behind the scenes of the constructor
The result
37
Call forms “The binding is dependant upon the way the function was called”
var obj = {};obj.f = f;obj.f();
obj.a; // 3
f(); // now there’s a global variable a whose value is 3
var newObj = new f();newObj.a;// 3
var str = ‘xyz’;f.apply(str,[]);str.a;// 3
function f(){this.a = 3};
Method form
Function form
Constructor form
Apply form
38
What about access rights?
There are no access rights in JavaScript Everything is public, there is no such thing as
‘private’ The various function execution forms simply
deflate this important concept
However, it is possible to mimic a private access right for a field in an object
Done using closure
39
function Counter(){
var count = 0;
this.getValue = function(){ return count ;};
this.increase = function(){count ++;};
this.decrease = function(){count --;};
this.setValue = function(newVal){count = newVal;};
}var c = new Counter();
c.setValue(5);
c.increase();
c.getValue(); // 6
c. count; // undefined
public
public
public
public
private
40
Anonymous functions
Functions doesn’t have to have an identifier
They can be anonymous
Becomes very useful when combined with immediate execution of the function
41
Write a function that receives an array of objects and sets their showIndex
method to show their index in that array
42
Bad solution
function(objs){
for(var i=0,l=objs.length;i<l;i++) {
objs [i].showIndex = function(){
alert(i); }
}
}
What will be alerted?
43
Good solution
function(objs){
for(var i=0,l=objs.length;i<l;i++) {
objs[i].showIndex = ( function(t){ // a function that returns a function, t here is a local variable
return function() {// this function sees the local variable ‘t’ of the red function
alert(t);
} })(i); // executing the red function
}
}
44
“Everything should be made as simple as possible, but not simpler”
Albert Einstein
45
What happens when things are too simple
(the dark side of JavaScript)
46
Two scopes
In JavaScript there are two scopes only
The global scope The function scope
No block scope
47
Global as the default scope
The default scope for variable definition is the global scopefunction (){
var a = 3; // local variable
b = 4; // global variable
}
Whenever a function is executed in the function form, ‘this’ points out to the global scope And the function form is the simplest one => the one
most novice developers would use unwittingly It is very simple to pollute the global scope
48
Semicolon insertion
You don’t have to write semicolon at the end of a code line
The run-time compiler does it for you This may lead to errors that are hard to find
function f1 (){ return {val: 4};};
function f1 (){ return; {val: 4};};
var a = f1(); // undefined
What the developer wrote Behind the scenes of the function
The result
49
The ‘with’ keyword
Define a scope for a block Intended to be used as a short hand
a.b.c = a.b.d +a.b.e;
with(a.b){
c=d+e;
}
50
with(obj){
a = b
}
if(obj.a === undefined){
if(obj.b === undefined){
a=b;// two global variables
} else {
a = obj.b; // a is global, b is not
} else {
if(obj.b === undefined){
obj.a=b; // b is global , a not
} else {
obj.a = obj.b; // both not global
}
}
a\b (exist in obj) - +
- a=b; // two global variables a = obj.b; // a is global, b not
+ obj.a = b; // b is global, a is not obj.a = obj.b; // both not global
The ‘with’ keyword
51
Bitwise operators
JavaScript supports bitwise operators: & , |, ^ , >>, << , >>>
But JavaScript have only 64 bit number type
No integer
Bitwise operators are used for faster, close to the hardware computations
In JavaScript this is not the case
52
Numerical calculations
All calculations in JavaScript are floating point calculation 10 / 3 = 3.3333333333333335 Simply put – erroneous when the decimal
point is involve 0.1 + 0.2 = 0.30000000004
53
The utility parseInt
ParseInt(stingValue, radix)
Strings that start with 0x are treated as hexadecimal
Strings that start with 0 are treated as octal based
parseInt(“08”) and parseInt(“09”) returns undefined Used often when parsing dates
54
Remember this ?
Imperative With prototypes (object-based, but not object-
oriented) Functions are first-class entities Has lambda functions With closures Is weakly typed Has dynamic typing Has dynamic binding
55
Thank You