Why$talk$aboutJavaScript?$pages.di.unipi.it/ferrari/CORSI/AP/LECTURES/JS.pdf · 3...
Transcript of Why$talk$aboutJavaScript?$pages.di.unipi.it/ferrari/CORSI/AP/LECTURES/JS.pdf · 3...
![Page 1: Why$talk$aboutJavaScript?$pages.di.unipi.it/ferrari/CORSI/AP/LECTURES/JS.pdf · 3 JavaScriptblocks$! Use${$}$for$grouping;$notaseparate$scope$ js>var$x=3;$ js>x$ 3 js>{var$x=4;$x}$](https://reader033.fdocuments.in/reader033/viewer/2022050402/5f7fd2a4bc8fa2188e462935/html5/thumbnails/1.jpg)
1
JAVASCRIPT
Why talk about JavaScript?
! Very widely used, and growing o Web pages, AJAX, Web 2.0 o Increasing number of web-‐related applicaEons
! Some interesEng and unusual features o First-‐class funcEons -‐ interesEng o Objects without classes -‐ slightly unusual o Powerful modificaEon capabiliEes -‐ very unusual
! Add new method to object, redefine prototype, access caller …
! Many security, correctness issues o Not staEcally typed – type of variable may change … o Difficult to predict program properEes in advance
![Page 2: Why$talk$aboutJavaScript?$pages.di.unipi.it/ferrari/CORSI/AP/LECTURES/JS.pdf · 3 JavaScriptblocks$! Use${$}$for$grouping;$notaseparate$scope$ js>var$x=3;$ js>x$ 3 js>{var$x=4;$x}$](https://reader033.fdocuments.in/reader033/viewer/2022050402/5f7fd2a4bc8fa2188e462935/html5/thumbnails/2.jpg)
2
Design goals
! Brendan Eich’s 2006 ICFP talk o Make it easy to copy/paste snippets of code o Tolerate “minor” errors (missing semicolons)
o Simplified onclick, onmousedown, etc., event handling, inspired by HyperCard
o Pick a few hard-‐working, powerful primiEves
! First class funcEons for procedural abstracEon ! Objects everywhere, prototype-‐based
o Leave all else out!
Language basics
! JavaScript is case sensiEve o HTML is not case sensiEve; onClick, ONCLICK, … are HTML
! Statements terminated by returns or semi-‐colons (;) o x = x+1; same as x = x+1 o Semi-‐colons can be a good idea, to reduce errors
! “Blocks” o Group statements using { … } o Not a separate scope, unlike other languages
! Variables o Define a variable using the var statement o Define implicitly by its first use, which must be an assignment
! Implicit definiEon has global scope, even if it occurs in nested scope?
![Page 3: Why$talk$aboutJavaScript?$pages.di.unipi.it/ferrari/CORSI/AP/LECTURES/JS.pdf · 3 JavaScriptblocks$! Use${$}$for$grouping;$notaseparate$scope$ js>var$x=3;$ js>x$ 3 js>{var$x=4;$x}$](https://reader033.fdocuments.in/reader033/viewer/2022050402/5f7fd2a4bc8fa2188e462935/html5/thumbnails/3.jpg)
3
JavaScript blocks
! Use { } for grouping; not a separate scope js> var x=3; js> x 3 js> {var x=4; x} 4 js> x 4
! Not blocks in the sense of other languages o Only funcEon calls and the with statement cause a change of scope
JavaScript primiEve datatypes
! Boolean o Two values: true and false
! Number o 64-‐bit floaEng point, similar to Java double and Double o No integer type o Special values NaN (not a number) and Infinity
! String o Sequence of zero or more Unicode characters o No separate character type (just strings of length 1) o Literal strings using ' or " characters (must match)
! Special values o null and undefined o typeof(null) = object; typeof(undefined)=undefined
![Page 4: Why$talk$aboutJavaScript?$pages.di.unipi.it/ferrari/CORSI/AP/LECTURES/JS.pdf · 3 JavaScriptblocks$! Use${$}$for$grouping;$notaseparate$scope$ js>var$x=3;$ js>x$ 3 js>{var$x=4;$x}$](https://reader033.fdocuments.in/reader033/viewer/2022050402/5f7fd2a4bc8fa2188e462935/html5/thumbnails/4.jpg)
4
Objects
! An object is a collecEon of named properEes o Simple view: hash table or associaEve array
o Can define by set of name:value pairs ! objBob = {name: “Bob", grade: 'A', level: 3};
o New members can be added at any Eme ! objBob.fullname = 'Robert';
o Can have methods, can refer to this
! Arrays, funcEons regarded as objects o A property of an object may be a funcEon (=method)
o A funcEon defines an object with method called “( )” funcEon max(x,y) { if (x>y) return x; else return y;};
max.descripEon = “return the maximum of two arguments”;
More about funcEons
! DeclaraEons can appear in funcEon body o Local variables, “inner” funcEons
! Parameter passing o Basic types passed by value, objects by reference
! Call can supply any number of arguments o funcEonname.length : # of arguments in definiEon o funcEonname.arguments.length : # args in call
! “Anonymous” funcEons (expressions for funcEons) o (funcEon (x,y) {return x+y}) (2,3);
! Closures and Curried funcEons o funcEon CurAdd(x){ return funcEon(y){return x+y} };
![Page 5: Why$talk$aboutJavaScript?$pages.di.unipi.it/ferrari/CORSI/AP/LECTURES/JS.pdf · 3 JavaScriptblocks$! Use${$}$for$grouping;$notaseparate$scope$ js>var$x=3;$ js>x$ 3 js>{var$x=4;$x}$](https://reader033.fdocuments.in/reader033/viewer/2022050402/5f7fd2a4bc8fa2188e462935/html5/thumbnails/5.jpg)
5
FuncEon Examples
! Anonymous funcEons make great callbacks setTimeout(funcEon() { alert("done"); }, 10000)
! Curried funcEon funcEon CurriedAdd(x){ return funcEon(y){ return x+y} }; g = CurriedAdd(2); g(3)
! Variable number of arguments funcEon sumAll() { var total=0; for (var i=0; i< sumAll.arguments.length; i++) total+=sumAll.arguments[i]; return(total); } sumAll(3,5,3,5,3,2,6)
Use of anonymous funcEons
◆ Simulate blocks by funcEon definiEon and call var u = { a:1, b:2 }
var v = { a:3, b:4 } (funcEon (x,y) {
var tempA = x.a; var tempB =x.b; //local variables
x.a=y.a; x.b=y.b;
y.a=tempA; y.b=tempB
}) (u,v) // This works because objects are passed by reference
![Page 6: Why$talk$aboutJavaScript?$pages.di.unipi.it/ferrari/CORSI/AP/LECTURES/JS.pdf · 3 JavaScriptblocks$! Use${$}$for$grouping;$notaseparate$scope$ js>var$x=3;$ js>x$ 3 js>{var$x=4;$x}$](https://reader033.fdocuments.in/reader033/viewer/2022050402/5f7fd2a4bc8fa2188e462935/html5/thumbnails/6.jpg)
6
Old Emes: lambda calculus
! Expressions x + y x + 2*y + z
! FuncEons λx. (x+y) λz. (x + 2*y + z)
! ApplicaEon (λx. (x+y)) (3) = 3 + y
(λz. (x + 2*y + z))(5) = x + 2*y + 5
Higher-‐Order FuncEons
! Given funcEon f, return funcEon f ° f λf. λx. f (f x)
! How does this work?
(λf. λx. f (f x)) (λy. y+1)
= λx. (λy. y+1) ((λy. y+1) x)
= λx. (λy. y+1) (x+1)
= λx. (x+1)+1
![Page 7: Why$talk$aboutJavaScript?$pages.di.unipi.it/ferrari/CORSI/AP/LECTURES/JS.pdf · 3 JavaScriptblocks$! Use${$}$for$grouping;$notaseparate$scope$ js>var$x=3;$ js>x$ 3 js>{var$x=4;$x}$](https://reader033.fdocuments.in/reader033/viewer/2022050402/5f7fd2a4bc8fa2188e462935/html5/thumbnails/7.jpg)
7
Same procedure, Lisp syntax
! Given funcEon f, return funcEon f ° f (lambda (f) (lambda (x) (f (f x))))
! How does this work? ((lambda (f) (lambda (x) (f (f x)))) (lambda (y) (+ y 1))
= (lambda (x) ((lambda (y) (+ y 1))
((lambda (y) (+ y 1)) x))))
= (lambda (x) ((lambda (y) (+ y 1)) (+ x 1))))
= (lambda (x) (+ (+ x 1) 1))
Same procedure, JavaScript syntax
! Given funcEon f, return funcEon f ° f funcEon (f) { return funcEon (x) { return f(f(x)); }; }
! How does this work? (function (f) { return function (x) { return f(f(x)); }; ) (function (y) { return y +1; })
function (x) { return (function (y) { return y +1; }) ((function (y) { return y + 1; }) (x)); }
function (x) { return (function (y) { return y +1; }) (x + 1); }
function (x) { return ((x + 1) + 1); }
![Page 8: Why$talk$aboutJavaScript?$pages.di.unipi.it/ferrari/CORSI/AP/LECTURES/JS.pdf · 3 JavaScriptblocks$! Use${$}$for$grouping;$notaseparate$scope$ js>var$x=3;$ js>x$ 3 js>{var$x=4;$x}$](https://reader033.fdocuments.in/reader033/viewer/2022050402/5f7fd2a4bc8fa2188e462935/html5/thumbnails/8.jpg)
8
Basic object features
! Use a funcEon to construct an object funcEon car(make, model, year) { this.make = make; this.model = model; this.year = year; }
! Objects have prototypes, can be changed var c = new car(“WW”,”Beetle”,1938); car.prototype.print = funcEon () { return this.year + “ “ + this.make + “ “ + this.model;} c.print();
JavaScript funcEons and this
var x = 5; var y = 5; funcEon f() {return this.x + y;} var o1 = {x : 10} var o2 = {x : 20} o1.g = f; o2.g = f; o1.g() 15 o2.g() 25
Both o1.g and o2.g refer to the same function object Why are the results for o1.g() and o2.g() different ?
![Page 9: Why$talk$aboutJavaScript?$pages.di.unipi.it/ferrari/CORSI/AP/LECTURES/JS.pdf · 3 JavaScriptblocks$! Use${$}$for$grouping;$notaseparate$scope$ js>var$x=3;$ js>x$ 3 js>{var$x=4;$x}$](https://reader033.fdocuments.in/reader033/viewer/2022050402/5f7fd2a4bc8fa2188e462935/html5/thumbnails/9.jpg)
9
More about this
! Property of the acEvaEon object for fctn call o In most cases, this points to the object which has the funcEon as a property (or method).
o Example : var o = {x : 10, f : funcEon(){return this.x}}
o.f(); 10
this is resolved dynamically when the method is executed
Special treatment for nested methods
var o = { x: 10 f : funcEon() { funcEon g(){ return this.x } ; return g(); } }; o.f()
FuncEon g gets the global object as its this property !
![Page 10: Why$talk$aboutJavaScript?$pages.di.unipi.it/ferrari/CORSI/AP/LECTURES/JS.pdf · 3 JavaScriptblocks$! Use${$}$for$grouping;$notaseparate$scope$ js>var$x=3;$ js>x$ 3 js>{var$x=4;$x}$](https://reader033.fdocuments.in/reader033/viewer/2022050402/5f7fd2a4bc8fa2188e462935/html5/thumbnails/10.jpg)
10
Stack memory management
! Local variables in acEvaEon record of funcEon funcEon f(x) { var y = 3;
funcEon g(z) { return y+z;}; return g(x);
} var x= 1; var y =2;
f(x) + y;
AR and Parameter Passing
• function f (x) = { x = x+1; return x; }var y = 0; print (f(y)+y);
• pseudo-code • activation records
• pass-by-re
f
• pass-by-value
• f(y) • y • 0
• Control link
• x • Return result addr
• •
• f(y)
• f(y) • y • 0
• Control link
• x • Return result addr
• 0
• f(y)
![Page 11: Why$talk$aboutJavaScript?$pages.di.unipi.it/ferrari/CORSI/AP/LECTURES/JS.pdf · 3 JavaScriptblocks$! Use${$}$for$grouping;$notaseparate$scope$ js>var$x=3;$ js>x$ 3 js>{var$x=4;$x}$](https://reader033.fdocuments.in/reader033/viewer/2022050402/5f7fd2a4bc8fa2188e462935/html5/thumbnails/11.jpg)
11
Closures
! Return a funcEon from funcEon call funcEon f(x) {
var y = x; return funcEon (z){y += z; return y;}
}
var h = f(5);
h(3);
! Docs: h{p://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:Working_with_Closures
(Lexical) Closures
! FuncEon value is pair closure = 〈env, code 〉 ! When a funcEon represented by a closure is
called, o Allocate acEvaEon record for call (as always)
o Set the access link in the acEvaEon record using the environment pointer from the closure
![Page 12: Why$talk$aboutJavaScript?$pages.di.unipi.it/ferrari/CORSI/AP/LECTURES/JS.pdf · 3 JavaScriptblocks$! Use${$}$for$grouping;$notaseparate$scope$ js>var$x=3;$ js>x$ 3 js>{var$x=4;$x}$](https://reader033.fdocuments.in/reader033/viewer/2022050402/5f7fd2a4bc8fa2188e462935/html5/thumbnails/12.jpg)
12
FuncEon Argument and Closures
int x = 4;
fun f(y) = x*y;
fun g(h) =
let int x=7
in
h(3) + x;
g(f);
• x • 4
• access link set from closure
• Code • for f
• f • access
• Run-time stack with access links
• Code • for g
• h(3) • y • 3
• access
• g(f) • h
• access
• x • 7
• g • access
Summary: FuncEon Arguments
! Use closure to maintain a pointer to the staEc environment of a funcEon body
! When called, set access link from closure
! All access links point “up” in stack o May jump past acEv records to find global vars
o SEll deallocate acEv records using stack (lifo) order
![Page 13: Why$talk$aboutJavaScript?$pages.di.unipi.it/ferrari/CORSI/AP/LECTURES/JS.pdf · 3 JavaScriptblocks$! Use${$}$for$grouping;$notaseparate$scope$ js>var$x=3;$ js>x$ 3 js>{var$x=4;$x}$](https://reader033.fdocuments.in/reader033/viewer/2022050402/5f7fd2a4bc8fa2188e462935/html5/thumbnails/13.jpg)
13
Return FuncEon as Result
! Language feature o FuncEons that return “new” funcEons o Need to maintain environment of funcEon
! Example funcEon compose(f,g) {return funcEon(x) { return g(f (x)) }};
! FuncEon “created” dynamically o expression with free variables
values are determined at run Eme o funcEon value is closure = 〈env, code〉 o code not compiled dynamically (in most languages)
FuncEon Results and Closures fun mk_counter (init : int) = let val count = ref init
fun counter(inc:int) = (count := !count + inc; !count) in counter end
end; val c = mk_counter(1); c(2) + c(2);
• c • access
• Code for • counter
• Code for • mk_counter
• c(2) • access • inc • 2
• 1 • mk_counter(1)
• count • init • 1
• access
• counter
• mk_c
• Call changes cell value from 1 to 3
• 3
• ML
![Page 14: Why$talk$aboutJavaScript?$pages.di.unipi.it/ferrari/CORSI/AP/LECTURES/JS.pdf · 3 JavaScriptblocks$! Use${$}$for$grouping;$notaseparate$scope$ js>var$x=3;$ js>x$ 3 js>{var$x=4;$x}$](https://reader033.fdocuments.in/reader033/viewer/2022050402/5f7fd2a4bc8fa2188e462935/html5/thumbnails/14.jpg)
14
Closures in Web programming
! Useful for event handlers in Web programming: funcEon AppendBu{on(container, name, message) {
var btn = document.createElement('bu{on');
btn.innerHTML = name; btn.onclick = funcEon (evt) { alert(message); }
container.appendChild(btn);
}
! Environment pointer lets the bu{on’s click handler find the message to display
Summary: Return FuncEon Results
! Use closure to maintain staEc environment
! May need to keep acEvaEon records a~er return o Stack (lifo) order fails!
! Possible “stack” implementaEon o Forget about explicit deallocaEon o Put acEvaEon records on heap
o Invoke garbage collector as needed o Not as totally crazy as is sounds
May only need to search reachable data
![Page 15: Why$talk$aboutJavaScript?$pages.di.unipi.it/ferrari/CORSI/AP/LECTURES/JS.pdf · 3 JavaScriptblocks$! Use${$}$for$grouping;$notaseparate$scope$ js>var$x=3;$ js>x$ 3 js>{var$x=4;$x}$](https://reader033.fdocuments.in/reader033/viewer/2022050402/5f7fd2a4bc8fa2188e462935/html5/thumbnails/15.jpg)
15
ExcepEons
! Throw an expression of any type throw "Error2";
throw 42;
throw {toString: funcEon() { return "I'm an object!"; } };
! Catch try { } catch (e if e == “FirstExcepEon") { // do something
} catch (e if e == “SecondExcepEon") { // do something else
} catch (e){ // executed if no match above
}
Reference: http://developer.mozilla.org/en/docs/ Core_JavaScript_1.5_Guide :Exception_Handling_Statements
Object features
! Dynamic lookup o Method depends on run-‐Eme value of object
! EncapsulaEon o Object contains private data, public operaEons
! Subtyping o Object of one type can be used in place of another
! Inheritance o Use implementaEon of one kind of object to implement another kind of object
![Page 16: Why$talk$aboutJavaScript?$pages.di.unipi.it/ferrari/CORSI/AP/LECTURES/JS.pdf · 3 JavaScriptblocks$! Use${$}$for$grouping;$notaseparate$scope$ js>var$x=3;$ js>x$ 3 js>{var$x=4;$x}$](https://reader033.fdocuments.in/reader033/viewer/2022050402/5f7fd2a4bc8fa2188e462935/html5/thumbnails/16.jpg)
16
Concurrency
! JavaScript itself is single-‐threaded o How can we tell if a language provides concurrency?
! AJAX provides a form of concurrency o Create XMLH{pRequest object, set callback funcEon o Call request method, which conEnues asynchronously o Reply from remote site executes callback funcEon
! Event waits in event queue… o Closures important for proper execuEon of callbacks
! Another form of concurrency o use SetTimeout to do cooperaEve mulE-‐tasking
! Maybe we will explore this in homework …
JavaScript eval
! Evaluate string as code o The eval funcEon evaluates a string of JavaScript code, in scope
of the calling code
! Examples var code = "var a = 1"; eval(code); // a is now '1‘ var obj = new Object(); obj.eval(code); // obj.a is now 1
! Most common use o Efficiently deserialize a large, complicated JavaScript data
structures received over network via XMLH{pRequest
! What does it cost to have eval in the language?
![Page 17: Why$talk$aboutJavaScript?$pages.di.unipi.it/ferrari/CORSI/AP/LECTURES/JS.pdf · 3 JavaScriptblocks$! Use${$}$for$grouping;$notaseparate$scope$ js>var$x=3;$ js>x$ 3 js>{var$x=4;$x}$](https://reader033.fdocuments.in/reader033/viewer/2022050402/5f7fd2a4bc8fa2188e462935/html5/thumbnails/17.jpg)
17
Unusual features of JavaScript ! Some built-‐in funcEons
o Eval, Run-‐Eme type checking funcEons, …
! Regular expressions o Useful support of pa{ern matching
! Add, delete methods of an object dynamically o Seen examples adding methods. Do you like this? Disadvantages? o myobj.a = 5; myobj.b = 12; delete myobj.a;
! Redefine naEve funcEons and objects (incl undefined) ! Iterate over methods of an object
o for (variable in object) { statements }
! With statement (“considered harmful” – why??) o with (object) { statements }