Why JavaScript? 2 JavaScript JavaScript the language Web page manipulation with JavaScript and the DOM 1994 1995: Wanted interactivity on the web Server side interactivity: CGI Common Gateway Interface Batch oriented (fill in a form, get interactive results) "Heavy weight" client side interactivity: Java Applets Self contained part of a web page Interacts with the user + possibly a server Does not interact with the document itself (Interactive versions of Macromedia Flash not available until 1998) "Light weight" client side interactivity: Netscape LiveScript Script language for the web (introduced late 1995) Renamed to JavaScript (marketing!) Standardized version: ECMAscript (ECMA 262, ISO 16262) Also used in Flash, Firefox/Thunderbird UI, PDF files, MacOS Dashboard Widgets, PhotoShop, JavaScript 1: Example 3 JavaScript 2: Script files 4 A simple JavaScript example: In HTML, scripts are CDATA not parsed by browsers, validators <!DOCTYPE HTML PUBLIC > <HTML> <head> <title>hello, World!</title> <script type="text/javascript"> alert("hello, World!"); // Show an alert to the user </script> </head><body> </body></html> In XHTML, your inline code is by default PCDATA (parsed) if (a < b) the < will be interpreted as the start of a tag <script type="text/javascript"> /* <![CDATA[ */ your code /* ]]> */ </script> Better solution: Separate script file Test.html: <!DOCTYPE HTML PUBLIC > <HTML> <head> <title>hello, World!</title> </head> <body> <script type="text/javascript" src="example.js"></script> </body> </HTML> example.js: // Show an alert to the user alert("hello, World!");
JavaScript 3: Types and type checking 5 JavaScript 4: Control 6 Like many script languages: No static type checking Variables are always declared with "var", not with a type var myvar = "Testing"; myvar = 10; myvar = true; Example: Some calculations var secs_per_min = 60; var mins_per_hour = 60; var hours_per_day = 24; var secs_per_day = secs_per_min * mins_per_hour * hours_per_day; Special values: null (behaves like 0 in numeric context, false in boolean context) undefined (behaves like false in boolean context) Control structures are similar to Java if (condition) { else { switch / case for (var i= 0; i < 10; i++) { while (condition) { do { while (condition) break / continue try { throw new ; catch (e) { finally { try { throw "Something"; catch (e) { finally { // Comment /* Long comment */ JavaScript 5: Operators 7 JavaScript 6: Functions 8 Operators are similar to Java, C, C++ ==!= // equals (tries to convert types before comparison) ===!== // (strict equals no type conversion) + * / < > << >> >>>// left shift, right shift, unsigned right shift += = *= /= ++, &&, Functions: Declared using the "function" keyword Late type checking: Don't declare parameter types function get_secs(days) { var secs_per_min = 60; var mins_per_hour = 60; var hours_per_day = 24; var secs_per_day = secs_per_min * mins_per_hour * hours_per_day; return days * secs_per_day; var secs_per_week = get_secs(7); Checking whether functions exist: if (get_secs) { Important! Used to check the level of JavaScript support. Important! Used to check the level of DOM support.
JavaScript 7: Object-oriented 9 JavaScript 8: Constructors 10 Object oriented but not class based Can use constructors if you want to Individual objects can have their own methods or fields Names the type ("Person") var me = new Object(); me.name = "Jonas Kvarnström"; // Creates a "name" field me.phone = null; me.getname = function() { return this.name; var you = new Object(); you.name = "Jane Doe"; you.address = "somewhere"; Literal notation: function Person(name, phone) { this.name = name; this.phone = phone; this.getname = function() { return this.name; var me = new Person("Jonas Kvarnström", "2305"); Can still add methods / fields incrementally var me = { name: "Jonas Kvarnström", phone: null, getname: function() { return this.name; ; Only weak syntax checking possible me.address = "Somewhere"; me.setaddress = function(addr) { this.address = addr; alert(me.phone); // OK alert(you.phone); // No such property (runtime error) JavaScript 9: Adding new methods 11 JavaScript 10: Adding to prototype 12 Inheritance based on prototypes Each object inherits properties from a prototype object function Employee(name, phone, department) { this.name = name; this.phone = phone; this.department = department; var me = new Employee("Jonas", "2305", "IDA"); me.prototype = new Person(); // Inheritance on a per object level! me.getphone(); // works inherited function from prototype Set the prototype of a constructor method Default prototype for objects constructed using Employee function Employee.prototype = new Person(); // "extends Person" Can add properties to the prototype at any time! Incremental extension person.prototype.getphone = function() { return phone; Now all "person" objects have this method Works for built in classes too! if (!String.prototype.trim) { // If trim does not exist String.prototype.trim = function() { return this.replace(/^\s+/,"").replace(/\s+$/,"");
JavaScript 11: Arrays 13 JavaScript 12: Associative arrays 14 Arrays: Kind of like Java arrays Allocated with new operator, or [] syntax var names1 = new Array("Roger", "Moore"); var names2 = [ "Roger", "Moore" ]; var empty = new Array(10); Indexed using [] syntax names[0] == "Roger" empty[0] == undefined Have a.length property Example: var reply = prompt("what's your name?", ""); var names = reply.split(" "); for (var pos = 0; pos < names.length; pos++) { alert("one of your names is " + names[pos]); Useful array methods concat joins two arrays join joins array elements into string push(x), pop() slice() returns a subsection of the array splice() adds/removes elements sort() Arrays can be associative Can replace Map / HashMap in Java var phonenumbers = new Array(); phonenumbers["jonas"] = "070 xxxxxxx"; phonenumbers[ Martin"] = "070 xxxxxxx"; Can iterate over all keys for (var name in phonenumbers) { // Jonas, Martin, dosomethingwith(phonenumbers[name]); Properties and arrays: Different interfaces, same data structure var me = new Person("Jonas Kvarnström", null); me["name"] = "Jonas Kvarnström"; for (var prop in me) { /* iterate over "name", "phone", "getname" */ JavaScript 13: Strings 15 JavaScript 14: Dates 16 String Single or double quotes var myvar = 'asdf', othervar = "qwerty"; Fields: length General Methods charat, charcodeat, indexof, lastindexof fromcharcode // from sequence of Unicode values "abc def ghi".split(" ") == array containing "abc", "def", "ghi" substring, substr, slice, concat match, replace, search // regular expressions tolowercase, touppercase HTML related Methods anchor, link // HTML named anchor / hyperlink big, blink, bold, fixed, italics, small, strike, sub, sup Date Constructors var date = new Date(); // today var date = new Date("December 31, 2010 12:34:56"); var date = new Date(2010, 12, 31); Methods getyear(), getmonth(), getdate, getday() // and setters gethour(), getminute(), getsecond() // and setters getfullyear() // four digit year
JavaScript 15: History and Window 17 Browser specific JavaScript objects: history the page history history.back(), history.forward() history.go(delta) // 1 = back, 2 = 2 steps back,... history.go('www.ida.liu.se') // nearest URL containing 'www.ida.liu.se' window.location the current location URL window.location = "http://www.ida.liu.se"; // New history entry window.location.reload(); window.location.replace("http://www.ida.liu.se"); // No new entry