javascript
play

JavaScript Common Gateway Interface Batch oriented (fill in a - PowerPoint PPT Presentation

jonkv@ida Why JavaScript? 2 1994 1995: Wanted interactivity on the web Server side interactivity: CGI JavaScript Common Gateway Interface Batch oriented (fill in a form, get interactive results) "Heavy


  1. jonkv@ida Why JavaScript? 2  1994 ‐ 1995: Wanted interactivity on the web  Server ‐ side interactivity: CGI JavaScript ▪ 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) JavaScript – the language  "Light ‐ weight" client ‐ side interactivity: Netscape LiveScript Web page manipulation with JavaScript and the DOM ▪ 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, … jonkv@ida jonkv@ida JavaScript 1: Example JavaScript 2: Script files 3 4  A simple JavaScript example :  Better solution: Separate script file  In HTML, scripts are CDATA – not parsed by browsers, validators  Test.html: ▪ <!DOCTYPE HTML PUBLIC …> ▪ <!DOCTYPE HTML PUBLIC …> <HTML> <HTML> <head> <head> <title>Hello, World!</title> <title>Hello, World!</title> <script type="text/javascript"> </head> alert("Hello, World!"); // Show an alert to the user <body> </script> <script type="text/javascript" src="example.js"></script> </head><body>…</body></HTML> </body> </HTML>  In XHTML, your inline code is by default PCDATA (parsed)  example.js: ▪ if (a < b) – the “<“ will be interpreted as the start of a tag ▪ // Show an alert to the user ▪ <script type="text/javascript"> alert("Hello, World!"); /* <![CDATA[ */ … your code … /* ]]> */ </script>

  2. jonkv@ida jonkv@ida JavaScript 3: Types and type checking JavaScript 4: Control 5 6  Like many script languages: No static type checking  Control structures are similar to Java  Variables are always declared with " var ", not with a type  if (condition) { … } else { … } ▪ var myvar = "Testing";  switch / case myvar = 10; myvar = true;  for ( var i = 0; i < 10; i++) { … }  Example: Some calculations  while (condition) { … } ▪ var secs_per_min = 60;  do { … } while (condition) var mins_per_hour = 60;  break / continue var hours_per_day = 24; var secs_per_day = secs_per_min * mins_per_hour * hours_per_day;  Special values:  try { throw new …; } catch (e) { … } finally { … } ▪ null (behaves like 0 in numeric context, false in boolean context)  try { throw "Something"; } catch (e) { … } finally { … } ▪ undefined (behaves like false in boolean context)  // Comment  /* Long comment */ jonkv@ida jonkv@ida JavaScript 5: Operators JavaScript 6: Functions 7 8  Operators are similar to Java, C, C++  Functions : Declared using the " function " keyword  == != // equals (tries to convert types before comparison)  Late type checking: Don't declare parameter types ▪ function get_secs(days) {  === !== // (strict equals – no type conversion) var secs_per_min = 60;  + ‐ * / var mins_per_hour = 60;  < > var hours_per_day = 24;  << >> >>>// left shift, right shift, unsigned right shift 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.

  3. jonkv@ida jonkv@ida JavaScript 7: Object-oriented JavaScript 8: Constructors 9 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(); ▪ function Person(name, phone) { me.name = "Jonas Kvarnström"; // Creates a "name" field this .name = name; me.phone = null; this .phone = phone; me.getName = function () { return this.name; } this .getName = function () { return this .name; } } ▪ var you = new Object(); ▪ var me = new Person("Jonas Kvarnström", "2305"); you.name = "Jane Doe"; you.address = "somewhere";  Literal notation:  Can still add methods / fields incrementally ▪ var me = { ▪ me.address = "Somewhere"; name: "Jonas Kvarnström", phone: null, ▪ me.setAddress = function (addr) { this .address = addr; } getName: function () { return this.name; } };  Only weak syntax checking possible ▪ alert(me.phone); // OK ▪ alert(you.phone); // No such property (runtime error) jonkv@ida jonkv@ida JavaScript 9: Adding new methods JavaScript 10: Adding to prototype 11 12  Inheritance based on prototypes  Can add properties to the prototype at any time!  Each object inherits properties from a prototype object  Incremental extension ▪ function Employee(name, phone, department) { ▪ person. prototype .getPhone = function () { return phone; } this.name = name; ▪ Now all "person" objects have this method this.phone = phone;  Works for built ‐ in classes too! this.department = department; ▪ if (!String. prototype .trim) { // If trim does not exist } String. prototype .trim = function () { ▪ var me = new Employee("Jonas", "2305", "IDA"); return this .replace(/^\s+/,"").replace(/\s+$/,""); 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"

  4. jonkv@ida jonkv@ida JavaScript 11: Arrays JavaScript 12: Associative arrays 13 14  Arrays : Kind of like Java arrays…  Arrays can be associative  Allocated with new operator, or [] syntax  Can replace Map / HashMap in Java ▪ var names1 = new Array("Roger", "Moore"); ▪ var phoneNumbers = new Array(); var names2 = [ "Roger", "Moore" ]; phoneNumbers["Jonas"] = "070 ‐ xxxxxxx"; Useful array methods var empty = new Array(10); phoneNumbers[“Martin"] = "070 ‐ xxxxxxx"; concat – joins two arrays  Indexed using [] syntax join – joins array elements into string  Can iterate over all keys ▪ names[0] == "Roger" push(x), pop() ▪ for ( var name in phoneNumbers) { // ”Jonas”, ”Martin”, … ▪ empty[0] == undefined slice() – returns a subsection of the array doSomethingWith(phoneNumbers[name]); splice() – adds/removes elements  Have a .length property } sort()  Example: ▪ var reply = prompt("What's your name?", "");  Properties and arrays: Different interfaces, same data structure var names = reply.split(" "); ▪ var me = new Person("Jonas Kvarnström", null ); for ( var pos = 0; pos < names.length; pos++) { me["name"] = "Jonas Kvarnström"; alert("One of your names is " + names[pos]); for ( var prop in me) { /* iterate over "name", "phone", "getName" */ } } jonkv@ida jonkv@ida JavaScript 13: Strings JavaScript 14: Dates 15 16  String  Date  Single or double quotes  Constructors ▪ var myvar = 'asdf', othervar = "qwerty"; ▪ var date = new Date(); // today ▪ var date = new Date("December 31, 2010 12:34:56");  Fields: length ▪ var date = new Date(2010, 12, 31);  General Methods  Methods ▪ charAt, charCodeAt, indexOf, lastIndexOf ▪ getYear(), getMonth(), getDate, getDay() // and setters ▪ fromCharCode // from sequence of Unicode values ▪ getHour(), getMinute(), getSecond() // and setters ▪ "abc def ghi".split(" ") == array containing "abc", "def", "ghi" ▪ getFullYear() // four ‐ digit year ▪ 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

  5. jonkv@ida 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

Recommend


More recommend