Lecture 3: The Basics of JavaScript Wendy Liu CSC309F Fall 2007 Background Origin and facts 1 2 Needs for Programming Capability XHTML and CSS allows the browser to passively display static content How to provide/request for more services? How to provide dynamic information? How to handle demands from the client? How to respond instantly to user actions? Demand for programming capability Origin of JavaScript Created to provide programming capability at both the server and the client ends of a Web connection Originally known as LiveScript Official name - ECMAScript http://www.ecma-international.org/publications/standards/ecma-262.htm Three parts Core Operators, expressions, statements, and subprograms Client-side A collection of objects that support control of a browser and interaction with users XHTML-embedded scripts An XHTML document may include any number of embedded scripts Server-side A collection of objects in support of a Web server (e.g. communicating with DBMS) 3 4 Using Client-side JavaScript Embedded in XHTML documents (physically or logically) Interpreted by the browser Objects representing windows, menus, pop-ups, dialog boxes, text areas, anchors, frames, history, cookies, and input/output Transfer load from server to client Cannot replace all server-side computing, e.g. file operations, DB access, and networking Easy to implement event-driven computation Interaction with users Triggering computation on events Focus change, page and image loading, unloading, error and abort, selection, form submission, and mouse actions Generate new content dynamically Access and modify CSS properties and content of any XHTML element (through the Document Object Model (DOM)) Facts of JavaScript Variables need not be declared and are dynamically typed Objects are dynamic Number of data members and methods of an object may change during execution Prototype-based inheritance An object-based web scripting language Basic language and host facilities are provided by objects Not an object-oriented programming language Does not have classes Its objects serve both as objects and models of objects Does not support OO development paradigm Syntax is similar to Java Expression, assignment statements, and control statements 5 6 1
Scripting Language A scripting language is a programming language that is used to manipulate, customise, and automate the facilities of an existing system. In such systems, useful functionality is already available through a user interface, and the scripting language is a mechanism for exposing that functionality to program control. In this way, the existing system is said to provide a host environment of objects and facilities, which completes the capabilities of the scripting language. A scripting language is intended for use by both professional and nonprofessional programmers. To accommodate nonprofessional programmers, some aspects of the language may be somewhat less strict. -- ECMA-262 Getting Started with JavaScript Basics 7 8 Embedding in XHTML Directly <script type="text/javascript"> <!-- JavaScript code // --> </script> Indirectly <script type="text/javascript" src="test.js"></script> Location Within <head> Within <body> Evaluation Evaluation and Execution As document is parsed, in order Execution Statements outside functions When encountered Statements inside a function When the function is called Event handler <body onload= helloworld() > 9 10 <head> <title> Greetings </title> <script type="text/javascript"> <!-- document.write("top"); function f(){ document.write( f: "+x); // --> </script> </head> Example 1 <body> <p> A simple example: <br/> <script type="text/javascript"> <!-- var x=1; f(); document.write("; Bot: "+x); // --> </script> </p> </body> Syntactic Characteristics Identifiers or names Must begin with a letter, _, or $ No length limitation Case sensitive Comment // Comment out the rest of the line /* comment out within the enclosure*/ Semicolon (;) End of statement Interpreter may insert one if absent (be careful) return becomes return; x; x; 11 12 2
Number Primitive Types e.g. 72 7.2.72 72. 7e2.7E2 7.2e-2 String a string also string (null strings) Boolean true false Undefined undefined Null null The first three types also have predefined objects Control if then else switch Looping Control and Looping for( init ; control ; inc) while ( control ) do while for.. in for (property in object) { 13 14 Functions function fname ([arg1] [,, argn]) { [return [value];] Parameters Primitive types (string, number, boolean) are passed by value Object types are passed by reference Determining the number of actual parameters arguments.length Functions are objects Example 2 function f1(mylist) { var newlist = new Array(1, 2, 3); mylist[3] = 4; mylist = newlist; var list = new Array(6, 7, 8); f1(list); 15 16 Variables Dynamically typed Variables are not typed, values are Type is determined by the interpreter on each instance Declaration Explicit (recommended) var i = 12, count; // value is undefined Implicit msg = hello ; Scope Global Declared outside functions Any variable implicitly defined Local Explicit declarations inside functions var x=1; function f(){ var y = 2; function g(){ var z = 3; Scope Chain x: 1 y: 2 z: 3 global object call object of scope f() call object of scope g() 17 18 3
Example 3 var x=1; document.write("top: "+x); function f(){ document.write("; top f(): "+x); var x = 2, y=0; document.write("; mid f(): "+x); x=y; document.write("; before g(): "+x); function g(){ var z = 3; x=z+y; document.write("; in g(): "+x); g(); document.write("; after g(): "+x); f(); document.write("; Bottom: "+x); Top: 1; top f(): undefined; mid f(): 2; before g(): 0; in g(): 3; after g(): 3; Bottom: 1 Implicit conversion Coercion Examples Type Conversions August + 20 string August 20 string 7 * 3 number (21) 7 * Aug NaN As a number null is 0 undefined is NaN As Boolean 0, NaN, undefined, null, empty string is false all other numbers or strings are true true == 1, false == 0 Explicit conversion var num = 6, s = num.tostring(), s2 = num.tostring(2); var b = String( 2007 ), n = Number(b), m = b 0; 19 20 JavaScript Objects Objects are collections of properties Like associative arrays (or maps) var point = new Object(); point.x = 2; Each property can be Data property Primitive value Reference to other object Function or method (property) Objects are indirectly accessed by variables Like references The root object is Object Object definition is determined at run time. Properties can be added or modified anytime Object Constructors Special methods for creating and initializing properties of the new objects function Rectangle_area() { return this.width * this.height; function Rectangle(w,h) { this.width = w; this.height = h; this.area = Rectangle_area; var rec = new Rectangle(2,4); var a = rec.area(), b = rec[ area ](); rec.newfunction = newpredecleredfunc; 21 22 Alternatively function Rectangle(w,h) { this.width = w; this.height = h; this.area = function () { return this.width * this.height; var rec = new Rectangle(2,4); A Subtle Point Inheritance rec.area(); rec[ area ](); Rec.newFunction = newpredecleredfunc; 23 24 4
Prototype-based Inheritance Prototype Example function car(themake, themodel){ this.prototype = constructor.prototype; this.make = themake; this.model = themodel; var greencar = new car("toyota", "camry"); var redcar = new car("honda", "accord"); redcar.prototype.speed = function (i){ return i*2; document.write(greencar.make + " + greencar.model + "'s speed is " + greencar.prototype.speed(3)+ "<br/>"); document.write(redcar.make + " " + redcar.model + "'s speed is " + redcar.speed(5)); 25 26 Predefined Objects More Sophisticated JavaScript Useful Objects Native objects ( Built-in objects) Object, Function, Array, String, Boolean, Number, Math, Date, RegExp, Error Primitive types are automatically coerced into Objects Host objects Navigator Window Document 27 28 Dynamic length Array Elements may be primitive values or references Index starts from 0 Modify.length to change array size All array elements are allocated dynamically var a = new Array(); // empty array var b = new Array( dog, 3, 8.4); var c = new Array(10); // array of size 10 var d = [2, 5, a, b ]; c[15] = hello ; // implicit extension length join() reverse() sort() concat() Array Properties and Methods slice() splice() push() / pop() shift() / unshift() tostring() 29 30 5
Represents the browser Properties appname Browser name appversion Browser version platforms Client OS cookieenabled cpuclass browserlanguage online navigator Object document Object Container for all HTML-related objects Content nested inside <html> tag Methods open() Opens a stream to collect the output from any document.write() write() Appends text to document Properties URL 31 32 window Object Browser window itself Methods open(url,name,[options]) open a new window close() alert() popup alert prompt() user input Properties document width, height toolbar, menubar, scrollbar, status, location resizable screenx, screeny Keyboard input Input and Output alert( Passwords must be at least 4 characters. ); var question = confirm( Do you want to submit? ); var name = prompt( What is your name?, ); Screen output document.write( Name: + name); 33 34 Pattern Matching Patterns are specified as regular expressions Based on Perl s regular expressions Two approaches String object search( pattern ) return start position of a match returns -1 if no match replace( pattern, value ) match( pattern ) split( pattern ) RegExp object Strings and Regular Expressions match(regexpobj) Verify input var phone = "416-4403467"; if (phone.match(/\d{3-\d{7/)) return true; replace(regexpobj, str) Replace part of a string var str = "One elephant and two zebras"; var matches = str.replace(/two/,"three"); 35 36 6
\w An alphanumeric \d A digit \s A white space. Anything other than newline [abcde] Any of a,b,c,d,e [a-e] Same as above String Object Approach [^a-e] Anything but a to e exp?, exp+, exp* 0 or 1, 1 or more, 0 or more symbolic quantifiers exp{x Exactly x repeats exp{x, y At least x repeats, but no more than y repeats expa expb expa or expb /exp/i Match either upper or lowercase in exp RegExp Object Approach RegExp object var animalsearch = /bear/; var animalsearch = new RegExp( bear ); Methods exec(str) return the match from str test(str) returns true if match if (animalsearch.test( The little bear )) { alert( I found a bear ); 37 38 JavaScript Security Language/API limitations No file/directory access defined in the language No raw network access, limited to Load URLs Send HTML form data to web servers, CGI scripts, e-mail addresses same origin policy Can only read properties of documents and windows from the same origin host, port, protocol Privacy restrictions Cannot read history Cannot hide/show menubar, status line, scrollbars Cannot close a window not opened by itself 39 7