17 Javascript
17 Javascript
Introduction to JavaScript
slide 1
What’s a Scripting Language?
Language used to write programs that compute
inputs to another language processor
• One language embedded in another
– Embedded JavaScript computes HTML input to the browser
– Shell scripts compute commands executed by the shell
Common characteristics of scripting languages
• String processing – since commands often strings
• Simple program structure, define things “on the fly”
• Flexibility preferred over efficiency, safety
– Is lack of safety a good thing? (Example: JavaScript used for
Web applications…)
slide 2
Why JavaScript?
“Active” web pages
Web 2.0
• AJAX, huge number of Web-based applications
Some interesting and unusual features
• First-class functions - interesting
• Objects without classes - slightly
unusual
• Powerful modification capabilities - very unusual
– Add new method to object, redefine prototype, …
Many security and correctness issues
“The world’s most misunderstood prog.
language” slide 3
Common Uses of JavaScript
Form validation
Page embellishments and special effects
Navigation systems
Basic math calculations
Dynamic content manipulation
Sample applications
• Dashboard widgets in Mac OS X, Google Maps,
Philips universal remotes, Writely word
processor, hundreds of others…
slide 4
Example 1: Add Two
Numbers
<html>
…
<p> … </p>
<script>
var num1, num2, sum
num1 = prompt("Enter first number")
num2 = prompt("Enter second number")
sum = parseInt(num1) + parseInt(num2)
alert("Sum = " + sum)
</script>
…
</html>
slide 5
Functions
Functions are objects with method called “( )”
• A property of an object may be a function (=method)
– function max(x,y) { if (x>y) return x; else return y;};
– max.description = “return the maximum of two arguments”;
• Local declarations may appear in function body
Call can supply any number of arguments
• functionname.length : # of arguments in definition
• functionname.arguments.length : # arguments in call
• Basic types are passed by value, objects by reference
“Anonymous” functions
• (function (x,y) {return x+y}) (2,3);
slide 6
Examples of Functions
Curried functions
– function CurriedAdd(x) { return function(y){ return
x+y} };
– g = CurriedAdd(2);
– g(3)
Variable number of arguments
– function 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)
slide 7