Presentation is loading. Please wait.

Presentation is loading. Please wait.

JavaScript for.Net Developers The things you need to know Pavel Kolev www.pavelkolev.com.

Similar presentations


Presentation on theme: "JavaScript for.Net Developers The things you need to know Pavel Kolev www.pavelkolev.com."— Presentation transcript:

1 JavaScript for.Net Developers The things you need to know Pavel Kolev www.pavelkolev.com

2 2 1.History of the Web 2.The Good, The Bad and the Evil 3.The Future Table of Contents

3 History of the Web

4 4  Just a document viewer, not a platform  It’s not a page – it’s a scroll  The good and the bad  Custom tags  Make the evolution possible  Accept bad html  Not so many tags – lets have ids and classes  No control over the presentation HTML

5 5 Runoff GML TEXScribe( ) LATEXSGML HTML XML GML: :h1.Gosho :ol :li.Pesho :li.Ivan :eol. … ::ol. … SGML – IBM government, CERN HTML – Simplified SGML

6 6  CSS isn’t bad. You just don’t understand it like I do.  Designed for paper printing.  The good and the bad  Not implementable – every specification fails  Complicated selector management (imagine no tools and !important)  Not intended for dynamic content  No modularity – different modules on the page with different style  Naming CSS

7 7 CSS vs JavaScript CSS background-color font-size list-style-type z-index float JavaScript(DOM) backgroundColor fontSize listStyleType zIndex cssFloat / styleFloat

8  Document Object Model  At first not all elements are scriptable (MS makes them all)  The good and the bad  document.write  Useless #textnode for whitespace  document.documentElement – return html  Hell a lot of a pointers The DOM

9 9  Pointers  Child (firstChild, lastChild)  Siblinds (nextSibling, previousSibling)  Parent (parentNode)  Children (childNodes)  You just need firstChild and nextSibling  node.property vs node.getAttribute (W3C fault – JAVA style)  node.className should be node.classNames The DOM - nodes

10 10  document.createElement – does not add it to the DOM  node.appendChild(newNode)  node.replaceChild(new, old) is actually old.parentNode.replaceChild(new, old)  node.removeChild(old) is actually old.parentNode.removeChild(old) – in IE you should remove all event handlers because of memory leaks  All browsers implemented MS’s innerHTML which acts like a parser (W3C does not provide access to HTML parser) The DOM – nodes operations

11 But meanwhile JavaScript happened

12  The Mosaic browser introducing the  The Netscape startup getting Brendan Eich on board  JavaScript JavaScript – the beginning Java (syntax) LiveScript Self (prototypes) Scheme (functions model)

13 13  The language of the web should have been JAVA  In Netscape 2.0 we got LS both on server and client  Netscape & Sun vs Microsoft  We kill LavaScript  JScript  Making the standart – W3C, ISO, ECMA  Can’t use the name so call it ECMAScript  Microsoft declares victory and leave the field JavaSceript – the early years

14 14  Netscape with bad business model  Microsoft moves to the X – Internet and.NET  JS should have died with Netscape as all languages do  Microsoft – the good guy  JScript  Generelized document model – made the DOM good enough  XMLHttpRequest(AJAX) – the second surprise to MS and the reason the web survived  The AJAX revolution succeeded because of the goodness of JS JavaScript and Microsoft

15 The Good, The Bad and the Evil

16 16  The need of interactivity in the browsers – HyperCards (Apple)  Brilliant ideas but not enough time to fix all the bugs during the browser wars  The greatest discovery of 21 st century – JS has good parts  The bad parts reasons  Legacy – coping some of the JAVA problems  Make it easy for newbies – “;”, global object – great or not  Too little time to design, develop and ship  The bad parts can be avoided and it’s a brilliant language JavaScript in short

17 17  Its all about objects  Objects in JS are not instances of a Class  Object – dynamic collection of properties  Each property has a key string that is unique within that object  get, set, delete  Think of them as hash tables JavaScript – all about Objects

18 18 JavaScript Types  JavaScript is NOT a typeless language  JavaScript is a loosely typed language – you don’t declare the data types of the variables explicitly  Types – Number, Boolean, String, Array, Function, Date, RegExp  Use var for declaration

19 19  Declares AND initializes variable within function  You do not specify type  JavaScript does not respect block scope  Declaration is split in 2 parts:  the declaration part is hoisted at the top of the function and initialized with undefined  the initialization part turns into ordinary assign statement var statement var a = “gosho”;

20 20 Number  Only one type for Number – no Integer, BigInteger, Float, Double etc… which makes the language easier for beginners  Using 64 – bit floating point  Using “Double” (IEEE-754) to represent numbers  Associative Law does not hold  Inherits from Number.prorotype (a + b) + c === a + (b + c)

21 21  Inherited from JAVA. Should be in Number Math object  abs  acos  asin  atan  atan2  ceil  cos  exp  floor  log  max  min  pow  random  round  sin  sqrt  tan  E  LN10  LN2  LOG10E  LOG2E  PI  SQRT1_2  SQRT2

22 22  Special Number – Not a Number  NaN – a number which is not any real number  With bad math you get NaN instead of error NaN NaN === NaN // false NaN !== NaN // true

23 23  Got it right  Exactly 2 Boolean values in the language:  true  false Boolean

24 24  Why we call them strings? They don’t look like strings?  No separate character type  A sequence of 0 or more 16 bit Unicode characters  Similar strings are equal (===)  Strings are immutable  You can use both ‘’ and “” for strings  Multiline strings String var myString = “This is a sample multiline \ string that will cause error”;

25 25  Numbers to Strings  Strings to number Strings var myNum = Number(str); var mySecondNum = +str; var myThirdNum = parseInt(“123mm”) // result in 123 var myForthNum = parseInt(“08”) // result in 0 var myFifthNum = parseInt(“08”, 10) // result in 8 var myString = num.toString(); var mySecondString = String(num);

26 26 String methods  charAt  charCodeAt  compareLocale  concat  indexOf  lastIndexOf  localeCompare  match  replace  search  slice  split  substring  toLocaleLowerCase  toLocaleUpperCase  toLowerCase  toString  toUpperCase  trim  length

27 27 Trim if(typeOf String.prototype.trim !== ‘function’) { String.prorotype.trim = function() { return this.replace(placeRegExHere); }}

28 28  There are no Arrays in JavaScript  JavaScript use objects to simulate array  Indexes are converted to strings and used as keys to retrieving values  You don’t have the speed advantage  No need to provide initial length of the array – they don’t actually have a length  We have length property  Don’t use for in with arrays – order of iteration is not guaranteed Array

29 29  Array litteral uses []  Can contain anything because it is object  Will fill the empty with udnefined Array literals var arr = [1, “pesho”, function() { … }]; arr.length === 3; // true arr[arr.length] = true;

30 30 Array methods  concat  every  filter  forEach  indexOf  join  lastIndexOf  map  pop  push  reduce  reduceRight  reverce  shift  slice  some  splice  toLocaleString  toString  unshift

31 31  Sorting  forEach  Removing items from the array  delete  splice Array methods arr.sort(function(a, b) { // my sorting function }); arr.forEach(function(item, index, array) { // do what you want }); delete arr[5]; // will leave undefined arr.splice(index, 1); // will reorder array

32 32  Date – based on JAVA’s Date  RegExp  All values are objects except for 2  null – value that isn’t anything  undefined – lack of value  default for variables and parameters  value for missing members of objects  probably not the best name “undefined” Other (before the major)

33 33  typeof – returns a string representing the type of a value  falsy values – if you put it in if statement you get to else branch  false // “false” is true  null  undefined  0 // “0” is true  “”  NaN Other (before the major) typeof null === ‘object’ // true typeof array === ‘object’ // true but we have Array.isArray

34 34  JSON.parse – parse json object  JSON.stringify – make json object “to string”  Object.keys – returns array of all enumerable properties of obj  Object.create(obj, newMembers) – you can now inherit from null  Array.isArray – check if passed obj is array  Use ‘strict mode’ on top of function (nice survey in MS for IE9) Others

35 35  Object based vs Class based  Key – Value  Two kind of properties  data properties – value, writeable  accessor properties – get, set (available with ES5)  No initialization Objects var obj = { name: “Pesho” }; obj.class = 10;

36 36 Objects var obj = Object.defineProperties(Object.create(Object.prototype), { age: { value: 20, writeable: true, enumerable: true, configurable: true, get: function() {…}, set: function() {…} }}) Object.seal(obj); // prevents new prop & all are non-config Object.freeze(obj); // makes it immutable Object.getOwnPropertyNames(obj); // event not enumerables

37 37  Coming from C it has all the same operators  Arithmetic  + - * / %  Comparison  == != > = <=  Logical  && || !  Bitwise  & | ^ >> >>> <<  Ternary  ?: Operators

38 38  Used for both addition and concatenation  If both operands are numbers – add them else – convert them to strings and concatenate them  Bad part that works in JAVA but not here  HTML does not know about numbers + “$” + 1 + 2 = “$12”

39 39  If  switch – the value does not need to be number  while  do  for  break  continue  return  try/throw  with – evil do not use it, please, please  eval – evil do not use it, please, please Statements with(obj) { a = b; } obj.a = b; obj.a = obj.b; a = b; a = obj.b;

40 40  JavaScript is functional language – first class functions  functions can be passed as arguments to a function  functions can be returned from functions  The beaty and one of the best parts  One of the key idea and they make JavaScript so powerfull  Functions in JavaScript does it all – Method, Class, Constructor, Module  Produce instance of function object Functions function name () { … return null; }

41 41  Function expression  Function statement / declaration  Because of function hoisting function statement can be called before declaration Functions statement vs expression var myFunc = function myFuncName() { … } function myFunc() { … };

42 42  JavaScript does not respect {} scope  Only functions have scope  Variables declared inside a function are not visible outside of it Scope

43 43  Invocation  Suffix () operator containing 0 or more parameters separated by comma  Will ignore extra arguments and will fill the missing with undefined  no type checking  Return  You can return any type you want  By default always returns undefined; Invocation and return

44 44  Function form  myFunction(arguments); // ES3 -> global object, ES5 - undefined  Method form – when it is part of an object  obj.myFunction(arguments); // this will be obj  obj[“myFunction”](arguments);  Constructor form  new MyFunction(arguments); // new object is created and assigned to this and if there is no return, this will be returned  Apply / Call form  myFunc.apply(obj, [arguments]); // this will be obj How to call a function

45 45  Great idea! Of course not accepted.  Closure – the context of the inner function includes the scope of the outer function. The inner function has access to that context even when the parent has returned Closure var myFunc = (function () { var months = [“Jan”, “Feb” … ]; return function(n) { return months[n-1]; }}());myFunc(2);

46 46  Pseudo paramenter that all functions get  Contains all arguments from the invocation  Array-like object but not array  arguments.length – number of passed arguments  Use it as read-only arguments

47 47  Pseudo paramenter that all functions have  Reference to the object of invokation  Allows a method to know what object it is connected with  Key to prototypal inheritance this

48 48  Objects can be passed to functions and returned  objects are passed by reference not by value  objects are almost never copied which is great  The equality operator === compares references not values Reference

49 49 Pseudoclassical inheritance function Human (name) { this.name = name; } Human.prototype.myFunc = function () { … }; function Student(name) { this.name = name; } Student.prototype = new Human(); Student.prototype.otherFunc = function() { … };

50 50 Functional inheritance function human (name) { return { name: name, myFunc: function () { … } }} function student(name) { var that = human(name); that.otherFunc = function() { … }; return that; }

51 51  JavaScript unlike many other languages does not have Read which makes it possible to have Event loop  Free of races and deadlocks  One stack only  Low overhead  If a turn fails, the program continues Event loop

52 52  Declare all variables on top of function  Don’t create functions in loops – new function object will be created with each iteration  !!variable – converts variable to boolean  return a && a.member / return a || a.member  You can have private members with closure  ++ is Assembly language feature – don’t use it  Don’t use the global object  Use JSLint Tips

53 AJAX 2000-2005?

54 The future 12.01.2016

55 I believe this presentation is not going to end on time but if you have any questions… otherwhise contact me i.pavelkolev@gmail.com http://pavelkolev.com i.pavelkolev@gmail.com http://pavelkolev.com


Download ppt "JavaScript for.Net Developers The things you need to know Pavel Kolev www.pavelkolev.com."

Similar presentations


Ads by Google