330 likes | 483 Vues
Modifying webpage behavior using client-side scripting. Javascript. 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#.” James Shore, author.
E N D
Modifying webpage behavior using client-side scripting Javascript SE-2840Dr. Mark L. Hornick
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#.” • James Shore, author SE-2840 Dr. Mark L. Hornick
JavaScript affects the behavior of a web page via manipulation of the browser’s Document The browser requests a page. Structure: HTML5 Presentation: CSS • With JavaScript, you canmodify both structure and presentation after the page is loaded webpage 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
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
JavaScript is not Java • Java is a completely different high-level language invented by Sun Microsystems • Javascript was created in 1995 by Netscape • First called “Livescript” • …then “Javascript” as a marketing strategy • Sun was making headlines with Java at the same time SE-2840 Dr. Mark L. Hornick
Scripts intially had a bad reputation from abuse of their capabilities • Annoying pop-up ads • Malware/Spyware SE-2840 Dr. Mark L. Hornick
Today’s Javascript is purposely limited Due to Security issues, JavaScript can't directly interact with private system resources (files) of the computer running the browser • Although HTML5 includes “local storage” capabilities that can be accessed from JavaScript SE-2840 Dr. Mark L. Hornick
[Legacy slide] Enabling scripting in IE and Firefox SE-2840 Dr. Mark L. Hornick In Privacy/Content Settings in Chrome 48 Reqs installation of privacy extensionto block on FF 44
Embedding Javascript in a web page <!DOCTYPE html> <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
Javascript errors are reported via an Error Console when one is enabled Implementation and activation varies by browser SE-2840 Dr. Mark L. Hornick
Javascript is it’s own complete high-level programming language, with familiar elements • Variables • Constants • Expressions • Conditional control statements (if, else if, switch) • Looping and iteration (for, while, do…while) • Exception handling (try-catch) As well as some unfamiliar concepts: • No formal classes (instead uses prototypes) • There ARE classes now in JS6 (2016) • Weaktyping • Functions outside of objects • Global variables SE-2840 Dr. Mark L. Hornick
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 typevarmsg= “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 stringmsg= 23; // now it’s bound to an integer There are only a few primitive datatypes • boolean • number • string • null • undefined • symbol (new in JS6) Javascript 6 also now supports constant values via the constkeyword,and block-scoped variables with via the letkeyword. SE-2840 Dr. Mark L. Hornick
NaN and Infinity var1 = 1/0; // evaluates to Infinity (a numeric type) var1 = -1/0 // evaluates to –Infinity var1 = 1/”x”; // evaluates to NaN (Not a Number) NaN and Infinity are numeric types! SE-2840 Dr. Mark L. Hornick
Javascript automatically converts types var var1 = 4 + 7.0; is converted to a floating-point value var var2=“100” + 15; 15 is promoted to string; result=“10015” var var3= 15 +“100”; 15 is promoted to string; result=“15100” Mixing numbers and strings results in strings SE-2840 Dr. Mark L. Hornick
Aspects of weakly-typed data • Javascript has the following boolean globlal functions that allow you to inquire about a variable’s bound type: • isNaN( var ) // returns true if Not a Number • isFinite( var ) // returns true if a finite number • Infinity is +/- infinity (note: capital “I”); a numeric type • undefined indicates an unitialized variable • NaN 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
An explicit conversion is required to turn a string to a number var1 = parseInt(“10”); var1 = parseFloat(“3.14”); var1 = parseFloat(“abc”); The numeric value NaN is assigned when a string cannot be parsed. The opposite conversion from a numeric value to a String is done via: var1 = 100; // var1 contains numeric value 100 var1 = String(100); // var1 contains “100” SE-2840 Dr. Mark L. Hornick
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
Boolean false and truthy/falsy values boolean x = false; if( x ) // evaluates to false (duh) x = undefined; // evaluates to false in if( x ) x = NaN; // 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
Arrays in Javascript var myArray; // untyped and undefined myArray = new Array(); // size not needed myArray[0] = “Hello”; // array size now 1 myArray[1] = 1; // array size now 2 myArray[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
More on arrays var myArray = [0,1,2,3]; // declared & initialized myArray[4]= -1; // now [0,1,2,3,-1] myArray[6]= 8; // now [0,1,2,3,-1, undefined, 8] myArray[0]= “hello”; // legal! SE-2840 Dr. Mark L. Hornick
Javascript supports the concept of global functions function myMethod(param1, param2) { “use strict”; // don’t allow sloppy codevar localVar = param1 + … return localVar; } • 0 or more formal parameters • Formal parameters are not typed • Return value of function is not typed • return statement is optional • If no return statement, function returns “undefined” • Local variables have function scope and visibility • Note: no block { } scope in Javascript<ES6! Use the letkeyword in place of var for block-scoped variables in JS 6 & later SE-2840 Dr. Mark L. Hornick
Javascript supports the concept of global variables var x = “I’m global!”; function myMethod(param1, param2) { “use strict”; var localVar = … return localVar + x; // x is visible here } • Global variables are visible everywhere • Local variables are only visible in their function scope SE-2840 Dr. Mark L. Hornick
Scoping and hoisting function myMethod(param1) { “use strict”; // var x is accessible here (but undefined) due to hoisting x = 5; const z = 3; if( param1 > value ) { var x = 1; // x is function scoped let y = 2; // y is block scoped } // var x is accessible here; y is NOT } • JS < 6 does not support block scope SE-2840 Dr. Mark L. Hornick
Anonymous functions var adder = function(a, b) { “use strict”; return a+b; } var sum = adder(1,3); // called like a normal function! • Note: Recursion is not possible with anonymous functions since internally the function cannot refer to itself by name SE-2840 Dr. Mark L. Hornick
Fat arrow functions (JS6) var add = (a,b)=>a+b; var sum = add(1,2); // called like a normal function! • Similar to Java lambda’s SE-2840 Dr. Mark L. Hornick
JavaScript supports objects, but without needing formal classes* • JS6 supports the class keyword, but this approach is optional and is considered “syntactic sugar” • i.e. it doesn’t change the underlying mechanism, which is based on prototypes CS-422Dr. Mark L. Hornick
No-class objects via constructor functions function MyObject(param1, param2) { “use strict”;this.property1 = param1; // public attribute this.property2 = param2; // public attribute this.doSomething = function(…) { // public method // function body goes here } } var x = new MyObject(x,y); // creation • Looks like a regular function • Always use a capital letter for the function name • No formal attribute declarations • Use of “this” automatically creates a public attribute • Be careful; typos may introduce unwanted attributes SE-2840 Dr. Mark L. Hornick
Making attributes and methods private function MyObject(param1, param2) { “use strict”;var property1 = param1; // private attribute this.property2 = param2; // public attribute this.doSomething1 = function(…) { // public method // function body goes here } var doSomething2 = function(…) { // private method// function body goes here} } var x = new MyObject(x,y); // creation SE-2840 Dr. Mark L. Hornick
Literal objects var roscoe = { firstName: “Roscoe”, // public attr lastName: “Raider”, // public attr getFullname: function(){ // public method return this.firstName + this.lastName;}; } • This is a kind of Singleton for Javascript CS-422Dr. Mark L. Hornick
JS6 class approach class MyObject { “use strict”; constructor(param1, param2) {var property1 = param1; // private attribute this.property2 = param2; // public attribute this.doSomething1 = function(…) { // public method // function body goes here } // end constructor var doSomething2 = function(…) { // private method// function body goes here} } // end class var x = new MyObject(x,y); // creation (same as JS5) CS-422Dr. Mark L. Hornick
Using a Javascript constructor to create objects (same approach whether class-based or not) var x = newMyObject(“arg1”, “arg2”); x.setXXX(“arg1b”); var y = x.getXXX(); Always use ‘new’; otherwise the effect will be to simply call MyObjectas a normal function. • No instance of MyObject would be created. • The attributes would be added to the “window” object instanct SE-2840 Dr. Mark L. Hornick
JavaScript “core API” defines only a few native objects – the remainder come from the hosting environment (i.e. the browser) • 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) • 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-422Dr. Mark L. Hornick
Other Javascript features • Functions are actually objects! • Having their own properties and methods • Functions can be passed as arguments to other Functions • C/C++ can do this, but Java cannot • Functions can nest other Functions • Functions are called methods when they are defined within an object SE-2840 Dr. Mark L. Hornick