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

javascript
SMART_READER_LITE
LIVE PREVIEW

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


slide-1
SLIDE 1

JavaScript

JavaScript – the language Web page manipulation with JavaScript and the DOM

2

jonkv@ida

Why JavaScript?

 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, …

3

jonkv@ida

JavaScript 1: Example

 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>

4

jonkv@ida

JavaScript 2: Script files

 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!");

slide-2
SLIDE 2

5

jonkv@ida

JavaScript 3: Types and type checking

 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)

6

jonkv@ida

JavaScript 4: Control

 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 */

7

jonkv@ida

JavaScript 5: Operators

 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
  • += ‐= *= /=
  • ++, ‐‐
  • &&, ||

8

jonkv@ida

JavaScript 6: Functions

 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.

slide-3
SLIDE 3

9

jonkv@ida

JavaScript 7: Object-oriented

 Object‐oriented but not class‐based

  • Individual objects can have their own methods or fields

▪ 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:

▪ var me = { name: "Jonas Kvarnström", phone: null, getName: function() { return this.name; } };

  • Only weak syntax checking possible

▪ alert(me.phone); // OK ▪ alert(you.phone); // No such property (runtime error)

10

jonkv@ida

JavaScript 8: Constructors

 Can use constructors if you want to

  • Names the type ("Person")

▪ 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

▪ me.address = "Somewhere"; ▪ me.setAddress = function(addr) { this.address = addr; }

11

jonkv@ida

JavaScript 9: Adding new methods

 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"

12

jonkv@ida

JavaScript 10: Adding to prototype

 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+$/,""); } }

slide-4
SLIDE 4

13

jonkv@ida

JavaScript 11: Arrays

 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()

14

jonkv@ida

JavaScript 12: Associative arrays

 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" */ }

15

jonkv@ida

JavaScript 13: Strings

 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

16

jonkv@ida

JavaScript 14: Dates

 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

slide-5
SLIDE 5

17

jonkv@ida

JavaScript 15: History and Window

 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