570 likes | 729 Views
JavaScript for .Net Developers. The things you need to know. Pavel Kolev. www.pavelkolev.com. Table of Contents. History of the Web The Good, The Bad and the Evil The Future. History of the Web. HTML. Just a document viewer, not a platform It’s not a page – it’s a scroll
E N D
JavaScript for .Net Developers The things you need to know Pavel Kolev www.pavelkolev.com
Table of Contents • History of the Web • The Good, The Bad and the Evil • The Future
HTML • 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 GML: :h1.Gosho :ol :li.Pesho :li.Ivan :eol. … ::ol. … </ol> Runoff Scribe(< >) TEX GML SGML LATEX HTML XML SGML – IBM government, CERN HTML – Simplified SGML
CSS • 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 vs JavaScript CSS background-color font-size list-style-type z-index float JavaScript(DOM) backgroundColor fontSize listStyleType zIndex cssFloat / styleFloat
The DOM • 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 - nodes • 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 operations • 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)
JavaScript – the beginning Self (prototypes) Scheme (functions model) Java (syntax) LiveScript The Mosaic browser introducing the <img /> The Netscape startup getting Brendan Eich on board JavaScript
JavaSceript – the early years • 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
JavaScript and Microsoft • 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 in short • 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 21st 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 – all about Objects • 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 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
var statement var a = “gosho”; • 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
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)
Math object • E • LN10 • LN2 • LOG10E • LOG2E • PI • SQRT1_2 • SQRT2 • abs • acos • asin • atan • atan2 • ceil • cos • exp • floor • log • max • min • pow • random • round • sin • sqrt • tan • Inherited from JAVA. Should be in Number
NaN NaN === NaN // false NaN !== NaN // true Special Number – Not a Number NaN – a number which is not any real number With bad math you get NaN instead of error
Boolean • Got it right • Exactly 2 Boolean values in the language: • true • false
String var myString = “This is a sample multiline \ string that will cause error”; 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
Strings var myString = num.toString(); var mySecondString = String(num); 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 Numbers to Strings Strings to number
String methods • charAt • charCodeAt • compareLocale • concat • indexOf • lastIndexOf • localeCompare • match • replace • search • slice • split • substring • toLocaleLowerCase • toLocaleUpperCase • toLowerCase • toString • toUpperCase • trim • length
Trim if(typeOfString.prototype.trim !== ‘function’) { String.prorotype.trim = function() { return this.replace(placeRegExHere); } }
Array • 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 literals vararr = [1, “pesho”, function() { … }]; arr.length === 3; // true arr[arr.length] = true; Array litteral uses [] Can contain anything because it is object Will fill the empty with udnefined
Array methods • concat • every • filter • forEach • indexOf • join • lastIndexOf • map • pop • push • reduce • reduceRight • reverce • shift • slice • some • splice • toLocaleString • toString • unshift
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 • Sorting • forEach • Removing items from the array • delete • splice
Other (before the major) • 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) typeof null === ‘object’ // true typeof array === ‘object’ // true but we have Array.isArray • 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
Others • 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)
Objects var obj = { name: “Pesho” }; obj.class = 10; • 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 = 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
Operators • Coming from C it has all the same operators • Arithmetic • + - * / % • Comparison • == != > < >= <= • Logical • && || ! • Bitwise • & | ^ >> >>> << • Ternary • ?:
+ “$” + 1 + 2 = “$12” 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
Statements with(obj) { a = b; } obj.a = b; obj.a = obj.b; a = b; a = obj.b; 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
Functions function name () { … return null; } • 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 statement vs expression var myFunc = function myFuncName() { … } function myFunc() { … }; Function expression Function statement / declaration Because of function hoisting function statement can be called before declaration
Scope JavaScript does not respect {} scope Only functions have scope Variables declared inside a function are not visible outside of it
Invocation and return • 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;
How to call a function • 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
Closure var myFunc = (function () { var months = [“Jan”, “Feb” … ]; return function(n) { return months[n-1]; } }()); myFunc(2); • 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
arguments 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
this 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
Reference • 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
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() { … };
Functional inheritance function human (name) { return { name: name, myFunc: function () { … } } } function student(name) { var that = human(name); that.otherFunc = function() { … }; return that; }