Simple Javascript Example
sum = 0;
for (i = 1; i < 10; i++) {
sum += i*i;
}
CS 142 Lecture Notes: Javascript Slide 1
Factorial in Javascript
function fac(x) {
if (x <= 1) {
return 1;
}
return x*fac(x-1);
}
CS 142 Lecture Notes: Javascript Slide 2
Embedding Javascript
External Javascript File
<body>
...
<script type="text/javascript" src=“[Link]" />
<script type="text/javascript">
//<![CDATA[
alert("Page is loading"); Inline Code
//]]>
</script>
<p onclick="alert('I told you not to click on me!');">
Please do not click on this text.</p>
...
</body>
Event Handler
CS 142 Lecture Notes: Javascript Slide 3
Method Example
Object o = new Object();
[Link] = 0;
[Link] = function(inc) {
if (inc == undefined) {
inc = 1;
}
[Link] += inc;
return [Link];
}
CS 142 Lecture Notes: Javascript Slide 4
Constructor
function Rectangle(width, height)
{
[Link] = width;
[Link] = height;
}
r = new Rectangle(26, 14);
CS 142 Lecture Notes: Javascript Slide 5
Prototypes
function Rectangle(width, height) {
[Link] = width;
[Link] = height;
}
[Link] = function() {
return [Link]*[Link];
}
r = new Rectangle(26, 14);
a = [Link]();
CS 142 Lecture Notes: Javascript Slide 6
CS 142 Lecture Notes: Javascript Slide 7