CS424 Notes, 27 January 2012
- Where to Put Your JavaScript
- JavaScript is the language that is used for scripting web pages.
You can add JavaScript code to a web page inside a <script> element:
<script type="text/javascript"> . . // JavaScript goes here . </script>
The type="text/javascript is really optional, since JavaScript is the default -- and pretty much the only -- supported type of scripting. - You can also put JavaScript code in a separate file, a plain text file
with extension .js, and include that file into your page like this:
<script type="text/javascript" src="javascriptfile.js"></script>
This is exactly equivalent to typing the entire contents of the file into the body of the script element. You can't mix the two modes: If you have a src="...", you cannot also have JavaScript code inside the text element. Note that the final </script> is required. - The src location of a script file can be a URL, not just a simple file name.
- There is one more place to put JavaScript, discussed later.
- JavaScript is the language that is used for scripting web pages.
You can add JavaScript code to a web page inside a <script> element:
- Basic stuff
- JavaScript variables don't have types. All variables are declared as "var varName;", and any variable can point to any kind of value.
- Values do have types. Primitive types are number, string, and boolean. There is a lot of automatic type conversion, as in C. For example, "5"+3 is 8, with the string "5" being converted to a number. On the other hand, "5"+"3" is the string "53"! In addition to the boolean constants true and false, any value can be used used as a boolean. (Null, zero, the empty string, and undefined values are false. The value of a variable is undefined if it has not been assigned a value.)
- Most operators are the same as in Java, except that / always does real number division (so 1/2 is 0.5, not 0 as it would be in Java or C). Also, you can compare strings with == and != to test whether the characters in the two strings are the same.
- JavaScript has most of the same Math functions as Java, like Math.sin, Math.pow, and Math.random. JavaScript doesn't have the same kind of type-casting as Java, so to get a random integer, you would use, for example, Math.floor(6*Math.random()+1).
- JavaScript has the same control structures as Java. (In a for loop, remember to declare your for-loop variable with var, not int!)
- Functions
- Functions are defined with the key word function. Neither the function itself
nor its parameters have types. You can return any type of value or none at all. For
example:
function randomInt(max) { return Math.floor( max * Math.random() + 1 ); }
- Variables can be declared inside a function, using var. These variables are local variables in the function. If you use a variable in a function without declaring it, its a global variable.
- You can define a function inside another function. The nested function can only be used inside the function where it is defined.
- A function can be called with any number of arguments. All the arguments are available in a special, predefined array in the function named arguments.
- Recursion is supported
- Functions are defined with the key word function. Neither the function itself
nor its parameters have types. You can return any type of value or none at all. For
example:
- Anonymous functions
- One of the very coolest things about JavaScript is that it has
anonymous functions (or function literals). The syntax is
function (<formal-parameter-list>) { <statements> }
- A function literal can be assigned to a variable, and then the variable
name can be used just like a function. For example:
var f = function (x) { return 3*x; }; alert( f(3) ); // The value in the alert box is 9.
- Both function literals and the names of named functions can also be: stored in a data structure such as an array or an object; passed as a parameter to a function; returned as the return value of a function. In short, functions are "first class objects" in JavaScript: You can do the same things with functions as with any other kind of data. The feature is used extensively in actual code!!
- One of the very coolest things about JavaScript is that it has
anonymous functions (or function literals). The syntax is
- Arrays
- You can create an array by listing its elements inside [ and ]. For example:
var primes = [ 2, 3, 5, 7, 11, 17, 19, 23, 29 ];
This is the notation for an array literal, and you can do all the usual things with it, like pass it as a parameter. - Array elements are accessed, as usual, as primes[i]. The length is given as usual as primes.length, but JavaScript arrays are not fixed length.
- JavaScript arrays have many other functions. For example, if A is an array,
you can use A.push(item) and A.pop() to use the array like a stack.
The usual way to build up an array one element as a time is to start with an empty
array and then push items onto it:
var primes = [ ]; for (var i = 2; i < 100; i++) { if (isPrime(i)) // (Assume isPrime() is defines; it's not built-in.) primes.push(i); }
- You can create an array by listing its elements inside [ and ]. For example:
- Objects
- You can have objects in JavaScript without classes! An object is just a collection
of name/value pairs. You can create an object by listing the name/value pairs between
{ and }. Here are some syntax examples:
var coords = { x: 17, y: 42 }; // Then you can refer to coords.x and coords.y var rect = { length: 12, width: 5, area: function() { return this.length * this.width } }; // rect.area() is a method in the object!
These are object literals, and again you can use them any way you could use any other kind of value. - (Note: Use of this is mandatory in methods to refer to member variables in an object. You can't abbreviate "this.length" as "length" as you could in Java. A reference to "length" would be talking about a global variable named length.)
- You can tread objects like associative arrays. That is, instead of saying coords.x, you can say coords["x"]. You can even use a variable or expression in the [], if the value of the variable is a string that is the name of a member of the object.
- You can add a new member to an object at any time just by assigning a value to it. For example, coords.z = 87 will add z as a member variable of coords if it is not already there.
- You can have objects in JavaScript without classes! An object is just a collection
of name/value pairs. You can create an object by listing the name/value pairs between
{ and }. Here are some syntax examples:
- Classes and Constructors.
- You can also have classes in JavaScript, and you can use them to create objects with the new operator, just as in Java.
- Writing classes in JavaScript, however, is nothing like writing classes in Java.
In some sense, you don't define classes at all; you define constructors, which are
just functions. If a function is meant to be a constructor, it will assign values
to properties of this. These are the properties of the object that
is created when the function is called with the new operator. By convention, constructor names begin with
an upper case letter. The name of the constructor function is also the name of the
class. For example:
function Rect( length, width ) { this.length = length; this.width = width; this.area = function() { return this.length * this.width }; } var r1 = new Rect( 12, 5 ); // r1.length is 12, and r1.width is 5 var r2 = new Rect( 8, 3 ); alert( r1.area() ); // value in the alert box is 60.
- However, the usual way to define methods in a class is to assign them
as properties of the prototype of the constructor. This allows all
objects created by the constructor to share the same method. For example:
function Rect( length, width ) { this.length = length; this.width = width; } Rect.prototype.area = function() { return this.length * this.width }; Rect.prototype.grow = function(factor) { this.length = this.length * factor; this.width = this.width * factor; };
- Typed Arrays
- An ordinary JavaScript array can hold items of any type. Recently, typed arrays have been added as a standard part of JavaScript. WebGL uses them, and they should work in any browser that supports WebGL, but they are not part of WebGL and might be available in browsers that don't support WebGL.
- A typed array can only hold numbers of a certain type. The size of a typed array is fixed when it is created; you can't dynamically change its length.
- Typed array classes include Float32Array, Int32Array, Int16Array, Int8Array, Uint32Array, Uint16Array, Uint8Array. (The "U" means "unsigned", so for example, Uint8Array holds values from 0 to 255 while Int8Array holds values from -128 to 127.)
- Typed arrays are created with the new operator. You can provide the length
as a parameter to the constructor. Alternatively, you can provide an existing array
as the parameter, and the elements of that array will be copied into the typed array.
For example:
var coords = new Float32Array(64); // creates an array with space for 64 floats. var color = new Uint8Array( [ 255, 180, 180, 255 ] ); // an array of 4 8-bit ints.
- Once you have a typed array, you can you can do subscripting in the usual way, for example: coords[3]=17
- Event Handlers
- The third place where you can put JavaScript code is in event handlers.
An event handler is associated to some HTML element, and it will be executed in
response to certain events associated with the element. For example, the
<body> element has an event handler named onload. The event in
this case is the loading of the HTML document. The value of
the onload handler is some JavaScript code that will be executed as soon
as the entire document has been loaded into the web browser. An example of
using this is
<body onload="init()">
In this case, the JavaScript code is init() and executing it means executing the init function. Note that the event handler here is a function call not just the name of a function! In fact, you could use any JavaScript statement in an event handler. - There are many other event handlers. Every element has an onclick handler that
is called when the element is clicked. This is probably most useful with buttons:
<button onclick="doClick()">Click Me!</button>
-
Input elements generally have an onchange handler that is called whenever
the value of the element changes. For example, the onclick of a checkbox
is called whenever the user checks or unchecks the box:
<input type="checkbox" onclick="doCheck()" id="chckbx">
- To use this effectively, you might need to know the Document Object Model (DOM),
that is, how to refer to HTML elements and their properties in your JavaScript code.
For example, to tell whether the above checkbox is checked or not, you could say:
if ( document.getElementById("chckbx").checked )
- These in-element event handlers are a rather old-fashioned way of doing events, but they should be good enough for this class.
- The third place where you can put JavaScript code is in event handlers.
An event handler is associated to some HTML element, and it will be executed in
response to certain events associated with the element. For example, the
<body> element has an event handler named onload. The event in
this case is the loading of the HTML document. The value of
the onload handler is some JavaScript code that will be executed as soon
as the entire document has been loaded into the web browser. An example of
using this is