Javascript for C# and Java

70
Javascript for C# and Java John McFetridge [email protected] Silverclouddevelopment.com/videos/ javascript.mp4

description

Javascript for C# and Java . John McFetridge [email protected] 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. - PowerPoint PPT Presentation

Transcript of Javascript for C# and Java

History

Javascript for C# and Java John [email protected]

Silverclouddevelopment.com/videos/javascript.mp4Assumed backgroundJava or C#OOClassesObjectsInheritanceGravity is built with Object Oriented JSGravity High Level Library Overview

Javascript/CSS/HTML/SVG 2011 KUDELSKI GROUP / Company Confidential#This is the reason we need to know JS3HistoryStarted with NetscapeWanted to put interactivity back into browserMake it similar to Hypercard which made Macintosh programming easyCombined ideas of three languagesJavaScheme a dialect of LispSelf a language that came out of Xerox ParcProduced what was called LivescriptHistorySun and Netscape were partnering against MSSun wanted Java in the browser and kill LivescriptRelationship nearly broke upAndreessen suggested the name be changed to Javascript and this workedNot much in common with JavaSun claimed ownership of trademarkMS reversed engineered it and produced JScriptHistoryNetscape wanted to make Javascript a standard but only European Computer Manufacturers Association show interestName became ECMAScript however Javascript and Jscript also applyMost browsers are at ES3 with 5 on the wayResultLanguage developed in 2 weeks (ouch)Smalltalk took 8 yearsMany bad parts came form copying Java which copied C which copied FortranSemi colonGlobal variablesMade life easier for beginner but harder for proLanguage has great expressive power however bad parts are dangerousGmail is rumored to have 1M lines of JSEnvironmentsGreat cross platform toolAlways runs in Host EnvironmentRich web applicationsServer side with node.jsCreate rich cross phone appsSencha TouchJquery mobileJS is NOT JUST A TOOL FOR ADDING SIMPLE INTERACTION TO WEB PAGEJavaScript is a sloppy language, but inside it there is an elegant, better language .. Douglas CrockfordVar and Dynamic natureVar is placeholder for data including functionsCase sensitiveDefine a variable or functionvar tt ;tt = 123;tt = 123;Objects are fully dynamic so can even assign tt a functiontt = function();Always declare before using as a good practiceSmall set of primitive typesNumbersonly one type C# double (64 bit floating point)No number conversion issuesHex var n4 = 0xffBooleanTrue, falseUndefined and nullUndefined is value of variable with no valueObject .. unordered collection of key-value pairsPrimitive types (more)NaN not a numberPerform operation that assumes nums but failsvar a = 10 * f;Stringstring is a sequence of 0 or more 16-bit Unicode charactersEach character is 16 bitsNo char as in C#Make a string with one characterCan express literals with single or double quotesABC ABCLike C# they are immutable

ECMAScript is an object-oriented programming language supporting delegating inheritance based on prototypes

ArraysJust list of objects (hashtable where values located by key)var a = [];Var a = [1,2,3];0 indexed so a[1] = 2Updatea[2] = three; [1,2,three]Adda[3] = four; [1,2,three,four]Deletedelete a[1]; leaves a hole as length is same

ArraysAs above arrays can contain anything including other arraysvar a = [[1, 2, 3], [4, 5, 6]]; //2 dimensonala[1][2] = 6;a[0][0] = 1;Can access individual chars in a stringvar s = one;s[0]; o

String conversionsUse number-like string as operand in arithmetic operation it is converted to number except additionvar s1 = 1; s1 = 3 * s1; typeof s1; numberConvert number-like string to numberMulti by 1parseint()Convert anything to string just concatenate with var n = 1; n = + n; typeof n; stringC-style syntaxbut not a whole lot of itfunction everything() { var x = {a:10}, y = [1,2], z = function() { }; for(var p in y) { lbl: for(var i = 0; i < 10; i++) { switch(x[p]) { case 0: break; default: break lbl; } } } 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); } }}Similar to C, C++, Java, C#, but withObject, Array, and Function literalsAutomatic semicolon insertionRegular expressionsfor..inoperatorsAddition subtraction,multi,dividevar tt = 1 + 2; Modulo6 % 3Post and prefix var b = ++a Simple assignment var a = 1; typeof typeof tt ; //number

ConditionsThe if conditionThe if statementA condition in parentheses"is a greater than 2?"A block of code wrapped in {} that executes if the condition is satisfiedif (a > 2) { result = 'a is greater than 2'; }

Curly on same lineElseSimple or unlimitedif (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'; }

TernaryInstead of

var a = 1, result = ''; if (a === 1) { result = "a is one";} else { result = "a is not one"; }

var result = (a === 1) ? "a is one" : "a is not one";condition ? result1 : result2;.SwitchLike 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 matchLoopsWhilevar I =0; while(I < 10) {Some code}Do-whileDo {code block} while (condition);For (initialization,condition,increment)For (var i=0; i < 100; i++) {code};For-In enumerate keys(property names) of objectVar p = {prodid:66, section:products}for(var key in p) {See URL code

Matter of Truthmany values that JavaScript has that act false-yFalseNullUndefined (empty string}0 (zero makes sense in C)NaN (not a number)All other values are truth-yTesting for Null// C# example. Don't do this in JavaScriptif ( someString != null &&someString.length > 0 ) {//Do something here...}// Simplified JavaScript syntax to check for// undefined, null, & empty string valuesif ( someString ) {//Do something here...}

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

If falsish assign defaultUsing wrong comparison operatorsusing 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 == Operator0 == ' //true (zero) both are falshish0 == '0' //truefalse == '0' //truenull == undefined //true

Use the === or !== InsteadThey will not only check the value, but also check the type as wellThe results of these comparisons are probably more what you would expect in a strongly typed language// Expected Comparisons using the === Operator0 === '' //false (number 0 and empty string)0 === '0' //falsefalse === '0' //falsenull === undefined //false

All about ObjectsIt is object based language

Object is a dynamic collection of properties (hashtable )Different from C# where an object is class instanceEach property has key stringAlso called associative arrays since each property is associated with a string value that can be used to access itvar mycar = new Object(); mycar.make = ford;Or mycar[make] = ford;

ObjectsObject literals{} surround zero or more name/value pairsE.g.var emptyobject = {};var name= {First_name : john, //object initializerLast-name:mcfetridge //legal js nameupper:function(){return ddddd}}//embedvar flight = {airline: usair,number:40, departure:{ city:Gainesville, gate:2}}Console.writeln(flight.departure.gate); //2

Special objectsThese are values of type object and are distinguished by internal properties

Wrappers for primitives like Number,string and BooleanFunction built by function constructor Arrays .. enumerated list of objectsHave short notations called initializervar array = [1,2,3] == new Array(1,2,4)

FunctionsIt is word function with optional name and parms with body wrapped in {}This produces a function objectFirst classAssign to variablePassed as argument to a functionInherit from Function.prototypeMethods like ToString, CallHas prototype property which is the reference to future objects

Function Declaration(older form)Mandatory nameShort hand for var with function valueFunction foo() {}Expands toVar foo = function {};Which in turn becomes, where both are hoisted to top of scopeVar foo = undefined;Foo = function foo() {};Expression vs DeclarationIf first token is function then this is function Declaration

Function ExpressionCan be named or anonymousMust not start with function

//anonymousVar a = function(){return 3}// namedVar a = function bar(){ return 3}Functionsare first-class valuesfunction 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 declarationsThe name of a function refers to the function valueFunctions can be passed to other functionsor with anonymous function expressions.Anonymous function expression33ArgumentsWhen called a function gets a special parameter called arguments in addition to its parmsHas all arguments Array like object and has length propertyGenerally treat as read onlyFunction 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);Try/Catch/FinallyLets u deal with exceptions gracefullytry{undefinedfunction()}catch(e){//catch and just suppress error}

Finally lets use define a function that is always calledBrowser ObjectsWindowRepresents an open window in a browserIf document has frames browser creates one window object for the HTML document, and one additional window object for each frameNavigatorInfo about the browser such as name, userAgentScreenInfo about the users Screen like height and widthHistoryURLs visited by the user in this window

HTML DOM ObjectsDocument objectWhen an HTML document is loaded into a web browser, it becomes a document objectThe 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).ElementRepresents an html elementEventsallow JavaScript to register different event handlers on elements in an HTML documentToolsEditorCan be Notepad but there are IDE that have syntax checking built inVisual Studio expressGreat intellisense but no JSLint pluginAptana studio 3Good intellisenseJSLint built inWebkit Web Inspector, prefer ChromeGreat debuggerCSS inspectorJSLintSee JSLint.comPart 2Quick review of part 1Show gravityFamo.usVar and Functions HoistingDeclare and initialize variables in functionNo types Variable is visible anywhere in function2 partsdeclaration part gets hoisted to the top of the function and is initialized with undefinedplace where the original var statement was, it gets turned into an assignment statement so that the var gets removed

Var myvar = 0; //expands tovar myvar = undefined ; //hoisted to top of func . . myvar =0 //at original placeScopeDue to hoisting blocks do not have scopeOnly functions doDeclare all variables at function top not near where they will be used firstDeclare all functions before using

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";InvocationThe ( ) suffix operator surrounding 0 or more comma separated argsThese args are bound to parametersKey to a self executing functions that we will look at laterIf called with too many args the extra are ignored but are still available in arguments arrayIf called with too few the missing are undefinedArgumentsWhen called a function gets a special parameter called arguments in addition to its parmsHas all arguments Array like object and has length propertyGenerally treat as read onlyFunction 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);ThisReference to object of invocation which allows method to know object it is concerned withAllows a function object to service many functionsfunction 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 Hited.speak(says Hi"); //ted is invoker (this is ted) Ted says HiFunctions and Thishave special rules for thisvar obj = { 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);

Inside a function, this is bound to the object containing the function, if there is one.Properties of an object can be functions.Calls look like method calls.There is no receiver this is the global object, this.offset is undefined.Use Function.prototype.call to specify the this parameter.Show javascript.js 46OOIn classical languages objects derive behavior from classesClass foo: bar

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

Constructor FunctionsThe object literal syntax is great for setting up one of objects but sometimes youll want to mass produce objects that all have the same properties and methods. Theres nothing that makes a constructor function different from a regular javascript function. Its just an ordinary function that has the logic needed to create a new object instead of regular program logic. Its not a special language construct like a class is in Java or C#.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 objectconstructor.htmlCapitalize first letter 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);The problem now is we still have an add method inside of each point. Prototype 2ProtoTypeJavaScript objects also have one additional attribute: a pointer to another object. We call this pointer the objects prototype. If you try to look up a key on an object and it is not found, JavaScript will look for it in the prototype. It will follow the prototype chain until it sees a null value. In that case, it returns undefined.

Only Functions have the prototype property

Confusing51

var o1 = { };

o1.valueOf() === "[object Object]"

var o2 = {valueOf: function() { return 10; }};

o2.valueOf() === 10

Objectshave prototypes (__proto__ in non IE)Where does valueOf come from?Its in a prototype object.If the property isnt in the current object, check its prototype, etcCan be overridden by hiding in prototype chain.

See javascript.js52Prototype inheritanceMost controversial feature of the languageClassical language like c# uses classes first formulated in 1967Prototype school was developed at Xerox by Smalltalk people 20 years laterJust make an object you like LiteralsCreate

Prototype InheritanceAlso called differential inheritance, in which you make an object and you add stuff to it only to make it different from the object that it inherits fromNew object only contains differencesEvery object has a __proto__ property.Code reuse is done not by making class templates that are used to instantiate objects, but by creating new objects directly, and then making other new objects based on existing ones. The existing object is assigned as the prototype of the new object and then new behavior can be added to the new object.

Objectsinherit from other objectsvar point2d = { x:10, y:20 };var point3d = Object.create(point2d);point3d.z = 30;

var location = Object.create(point2d);location.name = "Mandalay Bay"

The prototype chain

Sharing state only one Copy put behavior hereES5 formerly could do this with user defined functionObjects inherit objects not types as C#PsuedoClassical inheritanceUse Constructors (new)See inheritance2.jsObjects in ES5can have both data properties and accessor properties// Data Propertyvar bankAccount = {

balance: 1257

} Sounds like C# but all properties are public

// Accessor PropertyObject.defineProperty(bankAccount , " balance ", { get: function () { return balance; }, set: function (value) { balance= value; } });

Cant intercept reads/writesAccessor property(Really only Interceptor)Optional settervar foo = {}; Object.defineProperty(foo, "bar", { get: function () { return bar; }, set: function (value) { bar = value; } }); foo.bar = 5;Simulating Namespaces with objects

Name collision is a big issue

Var pan = {//public propertyType:frying,Fry:function(){ console.log(frying); }}

//now we are in a namespace panConsole.log(pan.type); //frying//add a public propertyPan.quantity = 12;Object literalAll vars are public var pan = ( function () { var public = {}, grease = 12 //private //public property public.ingredient = bacon; return public; //return public parts}() );

Access public Console.log(pan.ingredient);

Simulate private and public vars(Note the red brackets)SELF Executing Anonymous functionClosure (nested functions)Context of inner func includes scope of outerInner func has that context even AFTER parent funcs have returnedOr if this makes no sense special object that combines a function and the environment in which it was created including any local varibles in scope at time the closure was created

function makeadder(x){ return InnerFunction(y){ return x+y; } };

var add5 = makeadder(5); // 5 is captured

console.log(add5(6));Var names = [zero,one,two,three];Var digName = function (n) {return names[n];}Alert(digName(2)); //twoReally bad as names is Global so evolve to:

Var digName = function (n) { var names = [zero,one,two,three]; return names[n];}

Much better as names is no longer global but inefficent so Closure to rescue

Closure Closure Var digName = ( function () {

var names = [zero,one,two,three]; return function (n) {return names[n];};} () ) //wrapping in parens causes immediate execution

1 digName is the returned function not whole function and HAS ACCESS to Names even though it the outer has already returned

C# classclass Name{string firstName{get;set;}string lastname{get;set;}}

Name test = new name(){firstName=John, lastname=mcfetridge};

We are Dealing with objects not classes in JS

template method pattern is implemented in terms of inheritance, which makes the structure of the pattern static and makes the derivatives of the hierarchy statically coupled to the base abstraction

Must first define the class then new the objectDownsidesNo native interfaces and abstract classes so harder to implement a factory pattern

retrievalflight.departure.gate //2Flight[departure][gate] //like a bagFlight.departure.time //undefinedValue can updated by assignment:Flight.airline = delta;If object does not have property it is augmentedFlight.equipment ={model:Boeing 727};So properties can be added o the fly something C# cannot due as JS is a functional language ReferenceObjects are passed by reference as shown belowTypeof performs reflection e.g.Typeof myname //string

Var temp = name;Temp.lastname = mcfetridge;Var myname = name.lastname;

Myname is mcfetridge because temp and myname are references to same objectEnumerationFor in can loop thru the properties of an objectIncludes all properties var temp ={first=john, last=mcfet} temp.foo = function () { }; for (prop in temp) { document.writeln(prop); }Will output first,last,fooIssue due to prototype we will look at later

Invocation MethodThisObject.methodName(args)This is set to thisobject and then the function can act on thisobjectsFunction formfunctionObject(arguments)This is the global objectNOT very usefulInvocation .. ConstructorFunction used to create new objectnew FunctionValue(args)New object created and assigned to thisConstructor If no explicit return then this is returnedApply form ..specify thisfunctionObj.apply(thisObject, args)functionObj.call(thisObject, arg)

static void Main(string[] args) { List names = new List() { "zero", "one", "two", "three" }; Action myAction = () => Console.WriteLine("value of name = {0}", names[2]); Program.RunMe(myAction); Console.ReadLine(); }

public static void RunMe(Action myaction) { if(myaction != null) myaction(); }C#Design patternsMVC should be considered as in Sencha products doMVVM can be implemented with Knockout.jsobserverables