Modifying webpage behavior using clientside scripting Javascript SE2840
Modifying webpage behavior using client-side scripting Javascript SE-2840 Dr. Mark L. Hornick 1
2007 quote: “HTML with Javascript is going to become the GUI technology of choice, killing off ‘rich client’ and desktop apps written in languages such as C, C++, Java and C#. ” l James Shore, author SE-2840 Dr. Mark L. Hornick 2
Java. Script affects the behavior of a web page via manipulation of the browser’s Document The browser requests a page. Structure: HTML 5 Presentation: CSS l With Java. Script, you can modify both structure and presentation after the page is loaded web page The browser returns the page. The user interacts with the browser Javascript embedded in the webpage is “executed” by the browser SE-2840 Dr. Mark L. Hornick 3
Familiar applications of Javascript § Cascading menus § Modify images on mouse “rollover” § Validate forms before submitting to server § Num of chars, non-blank input, non-alpha numerics, etc § Background (color, music) effects § “Simple” applications § Calendars, payment calculators, etc § “Complex” applications § Google docs § Gmail § Facebook SE-2840 Dr. Mark L. Hornick 4
Java. Script is not Java l Java is a completely different highlevel language invented by Sun Microsystems l Javascript was created in 1995 by Netscape l l First called “Livescript” …then “Javascript” as a marketing strategy l Sun was making headlines with Java at the same time SE-2840 Dr. Mark L. Hornick 5
Scripts intially had a bad reputation from abuse of their capabilities l Annoying pop-up ads l Malware/Spyware SE-2840 Dr. Mark L. Hornick 6
Today’s Javascript is purposely limited Due to Security issues, Java. Script can't directly interact with private system resources (files) of the computer running the browser • Although HTML 5 includes “local storage” capabilities that can be accessed from Java. Script SE-2840 Dr. Mark L. Hornick 7
[Legacy slide] Enabling scripting in IE and Firefox In Privacy/Content Settings in Chrome 48 SE-2840 Dr. Mark L. Hornick Reqs installation of privacy extension to block on FF 44 8
Embedding Javascript in a web page <!DOCTYPE html> <head> <script type=“text/javascript”> // Javascript code can be placed in the <head> or <body> // of an HTML document; other locations are not recommended </script> <charset=“UTF-8" /> <title>Example Javascript</title> </head> <body> <script type=“text/javascript” src=“demo. js”> /* Javascript can be placed inline or in an external. js file */ </script> </body> </html> The <script>…</script> tags tell the browser that the contained content is not HTML to be displayed, but Javascript to be interpreted. The Javascript code is not displayed to the user. SE-2840 Dr. Mark L. Hornick 9
Javascript errors are reported via an Error Console when one is enabled Implementation and activation varies by browser SE-2840 Dr. Mark L. Hornick 10
Javascript is it’s own complete highlevel programming language, with familiar elements Variables l Constants l Expressions l Conditional control statements (if, else if, switch) l Looping and iteration (for, while, do…while) l Exception handling (try-catch) As well as some unfamiliar concepts: l No formal classes (instead uses prototypes) l l l There ARE classes now in JS 6 (2016) Weak typing Functions outside of objects Global variables SE-2840 Dr. Mark L. Hornick 11
Javascript is a weakly (dynamically)typed language, unlike C++ or Java A variable doesn’t really have a type; rather, a variable is bound to a value of a specific type var msg = “hello”; // a variable bound to a string The variable can be dynamically bound to another type over the lifetime of a variable! msg= “hello”; // here it’s bound to a string msg = 23; // now it’s bound to an integer There are only a few primitive datatypes l l l boolean number string null undefined symbol (new in JS 6) Javascript 6 also now supports constant values via the const keyword, SE-2840 Dr. Mark and block-scoped variables with via. L. Hornick the let keyword. 12
Na. N and Infinity var 1 = 1/0; // evaluates to Infinity (a numeric type) var 1 = -1/0 // evaluates to –Infinity var 1 = 1/”x”; // evaluates to Na. N (Not a Number) Na. N and Infinity are numeric types! SE-2840 Dr. Mark L. Hornick 13
Javascript automatically converts types var 1 = 4 + 7. 0; is converted to a floating-point value var 2=“ 100” + 15; 15 is promoted to string; result=“ 10015” var 3= 15 +“ 100”; 15 is promoted to string; result=“ 15100” Mixing numbers and strings results in strings SE-2840 Dr. Mark L. Hornick 14
Aspects of weakly-typed data Javascript has the following boolean globlal functions that allow you to inquire about a variable’s bound type: l l l l is. Na. N( var ) // returns true if Not a Number is. Finite( var ) // returns true if a finite number Infinity is +/- infinity (note: capital “I”); a numeric type undefined indicates an unitialized variable Na. N represents a value that is “not a number”; a numeric type The typeof(var) function returns a string indicating a value’s type SE-2840 Dr. Mark L. Hornick 15
An explicit conversion is required to turn a string to a number var 1 = parse. Int(“ 10”); var 1 = parse. Float(“ 3. 14”); var 1 = parse. Float(“abc”); The numeric value Na. N is assigned when a string cannot be parsed. The opposite conversion from a numeric value to a String is done via: var 1 = 100; // var 1 contains numeric value 100 var 1 = String(100); // var 1 contains “ 100” SE-2840 Dr. Mark L. Hornick 16
Type coercion (promotion) var x = 1; var y = “ 1”; // note single quotes can also be used if( x=y ) {…} // assigns y to x; x is then evaluated as true if( x==y ) {…} // coerces x to string ‘ 1’, and evaluates to true if( x===y ) {…} // evaluates to false General rule: Always use === for comparisons SE-2840 Dr. Mark L. Hornick 17
Boolean false and truthy/falsy values boolean x = false; if( x ) // evaluates to false (duh) x = undefined; // evaluates to false in if( x ) x = Na. N; // evaluates to false in if( x ) x = null; // evaluates to false in if( x ) x = “”; // empty string; evaluates to false in if( x ) x = “ ”; // non-empty strings evaluate to true in if( x ) x = 0; // evaluates to false in if( x ) x = -1; // non-zero values evaluate to true in if( x ) Proceed with caution SE-2840 Dr. Mark L. Hornick 18
Arrays in Javascript var my. Array; // untyped and undefined my. Array = new Array(); // size not needed my. Array[0] = “Hello”; // array size now 1 my. Array[1] = 1; // array size now 2 my. Array[2]= new Array(); // array element 3 is another array If an array size is specified, and the number of elements assigned to the array exceeds the size of the array, the array grows itself! SE-2840 Dr. Mark L. Hornick 19
More on arrays var my. Array = [0, 1, 2, 3]; // declared & initialized my. Array[4]= -1; // now [0, 1, 2, 3, -1] my. Array[6]= 8; // now [0, 1, 2, 3, -1, undefined, 8] my. Array[0]= “hello”; // legal! SE-2840 Dr. Mark L. Hornick 20
Javascript supports the concept of global functions function my. Method(param 1, param 2) { “use strict”; // don’t allow sloppy code var local. Var = param 1 + … return local. Var; } l l 0 or more formal parameters Formal parameters are not typed Return value of function is not typed return statement is optional l l If no return statement, function returns “undefined” Local variables have function scope and visibility l Note: no block { } scope in Javascript<ES 6! Use the let keyword in place of var for block-scoped variables in JS 6 & later SE-2840 21 Dr. Mark L. Hornick
Javascript supports the concept of global variables var x = “I’m global!”; function my. Method(param 1, param 2) { “use strict”; var local. Var = … return local. Var + x; // x is visible here } l l Global variables are visible everywhere Local variables are only visible in their function scope SE-2840 Dr. Mark L. Hornick 22
Scoping and hoisting function my. Method(param 1) { “use strict”; // var x is accessible here (but undefined) due to hoisting x = 5; const z = 3; if( param 1 > value ) { var x = 1; // x is function scoped let y = 2; // y is block scoped } // var x is accessible here; y is NOT } l JS < 6 does not support block scope SE-2840 Dr. Mark L. Hornick 23
Anonymous functions var adder = function(a, b) { “use strict”; return a+b; } var sum = adder(1, 3); // called like a normal function! l Note: Recursion is not possible with anonymous functions since internally the function cannot refer to itself by name SE-2840 Dr. Mark L. Hornick 24
Fat arrow functions (JS 6) var add = (a, b)=>a+b; var sum = add(1, 2); // called like a normal function! l Similar to Java lambda’s SE-2840 Dr. Mark L. Hornick 25
Java. Script supports objects, but without needing formal classes* l JS 6 supports the class keyword, but this approach is optional and is considered “syntactic sugar” l i. e. it doesn’t change the underlying mechanism, which is based on prototypes CS-422 Dr. Mark L. Hornick 26
No-class objects via constructor functions function My. Object(param 1, param 2) { “use strict”; this. property 1 = param 1; // public attribute this. property 2 = param 2; // public attribute this. do. Something = function(…) { // public method // function body goes here } } var x = new My. Object(x, y); // creation l l l Looks like a regular function Always use a capital letter for the function name No formal attribute declarations l Use of “this” automatically creates a public attribute l Be careful; typos may introduce unwanted attributes SE-2840 Dr. Mark L. Hornick 27
Making attributes and methods private function My. Object(param 1, param 2) { “use strict”; var property 1 = param 1; // private attribute this. property 2 = param 2; // public attribute this. do. Something 1 = function(…) { // public method // function body goes here } var do. Something 2 = function(…) { // private method // function body goes here } } var x = new My. Object(x, y); // creation SE-2840 Dr. Mark L. Hornick 28
Literal objects var roscoe = { first. Name: “Roscoe”, // public attr last. Name: “Raider”, // public attr get. Fullname: function(){ // public method return this. first. Name + this. last. Name; }; } l This is a kind of Singleton for Javascript CS-422 Dr. Mark L. Hornick 29
JS 6 class approach class My. Object { “use strict”; constructor(param 1, param 2) { var property 1 = param 1; // private attribute this. property 2 = param 2; // public attribute this. do. Something 1 = function(…) { // public method // function body goes here } // end constructor var do. Something 2 = function(…) { // private method // function body goes here } } // end class var x = new My. Object(x, y); // creation (same as JS 5) CS-422 Dr. Mark L. Hornick 30
Using a Javascript constructor to create objects (same approach whether class-based or not) var x = new My. Object(“arg 1”, “arg 2”); x. set. XXX(“arg 1 b”); var y = x. get. XXX(); Always use ‘new’; otherwise the effect will be to simply call My. Object as a normal function. l l No instance of My. Object would be created. The attributes would be added to the “window” object instanct SE-2840 Dr. Mark L. Hornick 31
Java. Script “core API” defines only a few native objects – the remainder come from the hosting environment (i. e. the browser) l l String – similar to the Java String class Array – generic container/collection class Math - like the Java Math class Number, Boolean – wrapper classes similar to Java wrapper classes (Integer, Double etc) l l var x = 123; // x is treated as a Number var y = “ 123”; // y is treated as a String var z = new Number(“ 123”); // z is a Number Date – represents dates and times CS-422 Dr. Mark L. Hornick 32
Other Javascript features l Functions are actually objects! l l Functions can be passed as arguments to other Functions l l l Having their own properties and methods C/C++ can do this, but Java cannot Functions can nest other Functions are called methods when they are defined within an object SE-2840 Dr. Mark L. Hornick 33
- Slides: 33