1 / 70

Javascript for C# and Java

Javascript for C# and Java . John McFetridge jmcfet@bellsouth.net Silverclouddevelopment.com/videos/javascript.mp4. Assumed background. Java or C# OO Classes Objects Inheritance Gravity is built with Object Oriented JS. Gravity High Level Library Overview. Javascript /CSS/HTML/SVG.

orpah
Télécharger la présentation

Javascript for C# and Java

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Javascript for C# and Java • John McFetridge • jmcfet@bellsouth.net • Silverclouddevelopment.com/videos/javascript.mp4

  2. Assumed background • Java or C# • OO • Classes • Objects • Inheritance • Gravity is built with Object Oriented JS

  3. Gravity High Level Library Overview Javascript/CSS/HTML/SVG

  4. History • Started with Netscape • Wanted to put interactivity back into browser • Make it similar to Hypercard which made Macintosh programming easy • Combined ideas of three languages • Java • Scheme a dialect of Lisp • Self a language that came out of Xerox Parc • Produced what was called Livescript

  5. History • Sun and Netscape were partnering against MS • Sun wanted Java in the browser and kill Livescript • Relationship nearly broke up • Andreessen suggested the name be changed to Javascript and this worked • Not much in common with Java • Sun claimed ownership of trademark • MS reversed engineered it and produced JScript

  6. History • Netscape wanted to make Javascript a standard but only European Computer Manufacturers Association show interest • Name became ECMAScript however Javascript and Jscript also apply • Most browsers are at ES3 with 5 on the way

  7. Result • Language developed in 2 weeks (ouch) • Smalltalk took 8 years • Many bad parts came form copying Java which copied C which copied Fortran • Semi colon • Global variables • Made life easier for beginner but harder for pro • Language has great expressive power however bad parts are dangerous • Gmail is rumored to have 1M lines of JS

  8. Environments • Great cross platform tool • Always runs in Host Environment • Rich web applications • Server side with node.js • Create rich cross phone apps • Sencha Touch • Jquery mobile • JS is NOT JUST A TOOL FOR ADDING SIMPLE INTERACTION TO WEB PAGE • JavaScript is a sloppy language, but inside it there is an elegant, better language .. Douglas Crockford

  9. Var and Dynamic nature • Var is placeholder for data including functions • Case sensitive • Define a variable or function • var tt ; • tt = 123; • tt = “123”; • Objects are fully dynamic so can even assign tt a function • tt = function(); • Always declare before using as a good practice

  10. Small set of primitive types • Numbers • only one type C# double (64 bit floating point) • No number conversion issues • Hex • var n4 = 0xff • Boolean • True, false • Undefined and null • Undefined is value of variable with no value • Object .. unordered collection of key-value pairs

  11. Primitive types (more) • NaN not a number • Perform operation that assumes nums but fails • var a = 10 * ‘f’; • String • string is a sequence of 0 or more 16-bit Unicode characters • Each character is 16 bits • No char as in C# • Make a string with one character • Can express literals with single or double quotes • “ABC” ‘ABC’ • Like C# they are immutable • ECMAScript is an object-oriented programming language supporting delegating inheritance based on prototypes

  12. Arrays • Just list of objects (hashtablewhere values located by key) • var a = []; • Var a = [1,2,3]; • 0 indexed so a[1] = 2 • Update • a[2] = ‘three’; [1,2,’three’] • Add • a[3] = ‘four’; [1,2,’three’,four’] • Delete • delete a[1]; leaves a hole as length is same

  13. Arrays • As above arrays can contain anything including other arrays • var a = [[1, 2, 3], [4, 5, 6]]; //2 dimensonal • a[1][2] = 6; • a[0][0] = 1; • Can access individual chars in a string • var s = ‘one’; • s[0]; ‘o’

  14. String conversions • Use number-like string as operand in arithmetic operation it is converted to number except addition • var s1 = ‘1’; s1 = 3 * s1; typeof s1; ‘number’ • Convert number-like string to number • Multi by 1 • parseint() • Convert anything to string just concatenate with ‘’ • var n = 1; n = ‘’ + n; typeof n; ‘string’

  15. C-style syntaxbut not a whole lot of it Similar to C, C++, Java, C#, but with… Object, Array, and Function literals function everything() { var x = {a:10}, y = [1,2], z = function() { }; for(var p iny) { lbl: for(var i = 0; i < 10; i++) { switch(x[p]) { case 0: break; default: breaklbl; } } } while(true) { if(true) { this.x = 3 / (-this.f()) ? /foo/g : new String("hello") } else { do { try { throw 3; } catch(e) { debugger; return; } } while(false); } } } for..in Automatic semicolon insertion Regular expressions

  16. operators • Addition subtraction,multi,divide • var tt = 1 + 2; • Modulo • 6 % 3 • Post and prefix • var b = ++a • Simple assignment • var a = 1; • typeof • typeoftt ; //number

  17. Conditions • The if condition • The if statement • A condition in parentheses—"is a greater than 2?" • A block of code wrapped in {} that executes if the condition is satisfied • if (a > 2) { • result = 'a is greater than 2'; • } Curly on same line

  18. Else • Simple or unlimited if (a > 2 || a < -2) { result = 'a is not between -2 and 2'; } else if (a === 0 && b === 0) { result = 'both a and b are zeros'; } else if (a === b) { result = 'a and b are equal'; } else { result = 'I give up'; }

  19. Ternary • Instead of vara = 1, result = ''; if (a === 1) { result = "a is one"; } else { result = "a is not one"; } condition ? result1 : result2;. var result = (a === 1) ? "a is one" : "a is not one";

  20. Switch • Like c# var day=new Date().getDay();switch (day){ case 6:   x="Today it's Saturday";   break; case 0:   x="Today it's Sunday";   break; default:   x="Looking forward to the Weekend";} If no match

  21. Loops • While • var I =0; while(I < 10) { • Some code • } • Do-while • Do {code block} while (condition); • For (initialization,condition,increment) • For (var i=0; i < 100; i++) {code}; • For-In enumerate keys(property names) of object • Var p = {prodid:66, section:’products’} • for(varkey in p) { • See URL code

  22. Matter of Truth • many values that JavaScript has that act false-y • False • Null • Undefined • “” (empty string} • 0 (zero makes sense in C) • NaN (not a number) • All other values are truth-y

  23. Testing for Null • // C# example. Don't do this in JavaScript • if ( someString != null && • someString.length > 0 ) { • //Do something here... • } • // Simplified JavaScript syntax to check for • // undefined, null, & empty string values • if ( someString ) { • //Do something here... • }

  24. Set Default Value • // C# example. Don't do this in JavaScript • someString = someString ? someString : "default value"; • // JavaScript syntax to set a default value all we need to do is check the object itself • someString = someString || "default value"; If falsish assign default

  25. Using wrong comparison operators • using the == and != comparison operators, JavaScript tries to help you by coercing the two values into the same type . This can lead to confusing results as shown below: • // Unexpected Comparisons using the == Operator • 0 == ‘ ' //true (zero) both are falshish • 0 == '0' //true • false == '0' //true • null == undefined //true

  26. Use the === or !== Instead • They will not only check the value, but also check the type as well • The results of these comparisons are probably more what you would expect in a strongly typed language • // Expected Comparisons using the === Operator • 0 === '' //false (number 0 and empty string) • 0 === '0' //false • false === '0' //false • null === undefined //false

  27. All about Objects • It is object based language • Object is a dynamic collection of properties (hashtable) • Different from C# where an object is class instance • Each property has key string • Also called associative arrays since each property is associated with a string value that can be used to access it • var mycar = new Object(); mycar.make = ‘ford’; • Or mycar[‘make’] = ‘ford’;

  28. Objects • Object literals • {} surround zero or more name/value pairs • E.g. var emptyobject = {}; var name= { “First_name” : “john”, //object initializer “Last-name”:”mcfetridge” //legal js name upper:function(){return ddddd} } //embed var flight = { airline: “usair”, number:40, departure:{ city:’Gainesville’, gate:2 } } Console.writeln(flight.departure.gate); //2

  29. Special objects • These are values of type object and are distinguished by internal properties • Wrappers for primitives like Number,string and Boolean • Function built by function constructor • Arrays .. enumerated list of objects • Have short notations called initializer • var array = [1,2,3] == new Array(1,2,4)

  30. Functions • It is word function with optional name and parms with body wrapped in {} • This produces a functionobject • First class • Assign to variable • Passed as argument to a function • Inherit from Function.prototype • Methods like ToString, Call • Has prototypeproperty which is the reference to future objects

  31. Function Declaration(older form) • Mandatory name • Short hand for var with function value • Function foo() {} • Expands to • Var foo = function {}; • Which in turn becomes, where both are hoisted to top of scope • Var foo = undefined; • Foo = function foo() {}; • Expression vs Declaration • If first token is function then this is function Declaration

  32. Function Expression • Can be named or anonymous • Must not start with ‘function’ //anonymous Var a = function(){ return 3 } // named Var a = function bar(){ return 3 }

  33. Functionsare first-class values function sum(x, y) { return x + y; } var sum2 = function(x, y) { return x + y; } var sum3 = sum; var test = sum(3,4); function wrap(f) { return f(); } wrap(function() { return 5; }) Functions can be defined with function declarations… …or with anonymous function expressions. The name of a function refers to the function value Functions can be passed to other functions

  34. Arguments • When called a function gets a special parameter called arguments in addition to its parms • Has all arguments • Array like object and has length property • Generally treat as read only Function sum(){ var i, n = arguments.length, total = 0; for (i = 0; i < n; i +=1){ total += arguments[i]; } return total; } Var ten = sum(1,2,3,4);

  35. Try/Catch/Finally • Let’s u deal with exceptions gracefully • try{undefinedfunction()}catch(e){ //catch and just suppress error} • Finally lets use define a function that is always called

  36. Browser Objects • Window • Represents an open window in a browser • If document has frames browser creates one window object for the HTML document, and one additional window object for each frame • Navigator • Info about the browser such as name, userAgent • Screen • Info about the users Screen like height and width • History • URLs visited by the user in this window

  37. HTML DOM Objects • Document object • When an HTML document is loaded into a web browser, it becomes a document object • The document object is the root node of the HTML document and the "owner" of all other nodes:(element nodes, text nodes, attribute nodes, and comment nodes). • Element • Represents an html element • Events • allow JavaScript to register different event handlers on elements in an HTML document

  38. Tools • Editor • Can be Notepad but there are IDE that have syntax checking built in • Visual Studio express • Great intellisense but no JSLint plugin • Aptana studio 3 • Good intellisense • JSLint built in • Webkit Web Inspector, prefer Chrome • Great debugger • CSS inspector • JSLint • See JSLint.com

  39. Part 2 • Quick review of part 1 • Show gravity • Famo.us

  40. Var and Functions Hoisting • Declare and initialize variables in function • No types • Variable is visible anywhere in function • 2 parts • declaration part gets hoisted to the top of the function and is initialized with undefined • place where the original var statement was, it gets turned into an assignment statement so that the var gets removed Var myvar = 0; //expands to var myvar = undefined ; //hoisted to top of func …. …. myvar =0 //at original place

  41. Scope • Due to hoisting blocks do not have scope • Only functions do • Declare all variables at function top not near where they will be used first • Declare all functions before using

  42. function foo(){ var isTruth = 'true'; //C# style block scope thinking if (isTruth){ var local = "my value"; } nested(); function nested(){ //nested also has access to local Console.Log(local); //output "my value“ } } //cannot prevent but should declare all function variables at top of function not in place as in C# function foo() { var isTruth = 'true'; var local = "my value";

  43. Invocation • The ( ) suffix operator surrounding 0 or more comma separated args • These args are bound to parameters • Key to a self executing functions that we will look at later • If called with too many args the extra are ignored but are still available in arguments array • If called with too few the missing are undefined

  44. Arguments • When called a function gets a special parameter called arguments in addition to its parms • Has all arguments • Array like object and has length property • Generally treat as read only Function sum(){ var i, n = arguments.length, total = 0; for (i = 0; i < n; i +=1){ total += arguments[i]; } return total; } Var ten = sum(1,2,3,4);

  45. This • Reference to object of invocation which allows method to know object it is concerned with • Allows a function object to service many functions’ function speak(text){ var output = this.adjective + ' ' + text; console.log(output); } var bill = { adjective : "bill",speak: speak}; var ted= { adjective : "ted",speak: speak}; bill.speak(“says Hi"); //bill is invoker (this is bill) Bill says Hi ted.speak(“says Hi"); //ted is invoker (this is ted) Ted says Hi

  46. Functions and Thishave special rules for ‘this’ Properties of an object can be functions. varobj = { sum: function(x,y) { return x + y; } } obj.sum(3,4); var obj2 = { offset: 7; sum: function(x,y) { return x + y + this.offset; } } obj2.sum(3,4) === 14; var f = obj2.sum; f(3,4) === NaN; f.call(obj2, 3, 4); Calls look like method calls. Inside a function, ‘this’ is bound to the object containing the function, if there is one. There is no receiver – ‘this’ is the global object, ‘this.offset’ is undefined. Use Function.prototype.call to specify the ‘this’ parameter.

  47. OO • In classical languages objects derive behavior from classes • Class foo: bar

  48. Constructor Functions The object literal syntax is great for setting up one of objects but sometimes you’ll want to mass produce objects that all have the same properties and methods. There’s nothing that makes a constructor function different from a regular javascript function. It’s just an ordinary function that has the logic needed to create a new object instead of regular program logic. It’s not a special language construct like a class is in Java or C#. Expects to be used in conjunction with the new operator to construct objects In essence functions when used with the keyword new behave like factories This is set to object to be returned by the constructor Can also use Object.Create .. Really a ‘purer’ solution

  49. Capitalize first letter var Point = function (x, y) { this.x = x; this.y = y; this.add = function (otherPoint) { this.x += otherPoint.x; this.y += otherPoint.y; } } var p1 = new Point(3, 4); var p2 = new Point(8, 6); p1.add(p2); This inside Point is set to the newly created object constructor.html

  50. Prototype 2 The problem now is we still have an add method inside of each point. var Point = function (x, y) { this.x = x; this.y = y; } Point.prototype.add = function (otherPoint) { this.x += otherPoint.x; this.y += otherPoint.y; } var p1 = new Point(3, 4); var p2 = new Point(8, 6); p1.add(p2);

More Related