javascript for.net developers the things you need to know pavel kolev

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

Upload: august-martin

Post on 17-Jan-2016

228 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: JavaScript for.Net Developers The things you need to know Pavel Kolev

JavaScript for .Net Developers

The things you need to know

Pavel Kolevwww.pavelkolev.com

Page 2: JavaScript for.Net Developers The things you need to know Pavel Kolev

2

1. History of the Web

2. The Good, The Bad and the Evil

3. The Future

Table of Contents

Page 3: JavaScript for.Net Developers The things you need to know Pavel Kolev

History of the Web

Page 4: JavaScript for.Net Developers The things you need to know Pavel Kolev

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

Page 5: JavaScript for.Net Developers The things you need to know Pavel Kolev

5

HTML

Runoff

GML TEXScribe(< >)

LATEXSGML

HTML

XML

GML::h1.Gosho :ol:li.Pesho:li.Ivan:eol.…::ol.…</ol>

SGML – IBM government, CERN

HTML – Simplified SGML

Page 6: JavaScript for.Net Developers The things you need to know Pavel Kolev

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

Page 7: JavaScript for.Net Developers The things you need to know Pavel Kolev

7

CSS vs JavaScript

CSS

background-colorfont-sizelist-style-typez-indexfloat

JavaScript(DOM)

backgroundColorfontSizelistStyleTypezIndexcssFloat / styleFloat

Page 8: JavaScript for.Net Developers The things you need to know Pavel Kolev

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

Page 9: JavaScript for.Net Developers The things you need to know Pavel Kolev

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

Page 10: JavaScript for.Net Developers The things you need to know Pavel Kolev

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

Page 11: JavaScript for.Net Developers The things you need to know Pavel Kolev

But meanwhile JavaScript happened

Page 12: JavaScript for.Net Developers The things you need to know Pavel Kolev

The Mosaic browser introducing the <img /> The Netscape startup getting Brendan Eich on board JavaScript

JavaScript – the beginning

Java(syntax)

LiveScript

Self(prototypes)

Scheme(functions model)

Page 13: JavaScript for.Net Developers The things you need to know Pavel Kolev

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

Page 14: JavaScript for.Net Developers The things you need to know Pavel Kolev

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

Page 15: JavaScript for.Net Developers The things you need to know Pavel Kolev

The Good, The Bad and the Evil

Page 16: JavaScript for.Net Developers The things you need to know Pavel Kolev

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 in short

Page 17: JavaScript for.Net Developers The things you need to know Pavel Kolev

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

Page 18: JavaScript for.Net Developers The things you need to know Pavel Kolev

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

Page 19: JavaScript for.Net Developers The things you need to know Pavel Kolev

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”;

Page 20: JavaScript for.Net Developers The things you need to know Pavel Kolev

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)

Page 21: JavaScript for.Net Developers The things you need to know Pavel Kolev

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

Page 22: JavaScript for.Net Developers The things you need to know Pavel Kolev

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 // falseNaN !== NaN // true

Page 23: JavaScript for.Net Developers The things you need to know Pavel Kolev

23

Got it right Exactly 2 Boolean values in the language:

true false

Boolean

Page 24: JavaScript for.Net Developers The things you need to know Pavel Kolev

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”;

Page 25: JavaScript for.Net Developers The things you need to know Pavel Kolev

25

Numbers to Strings

Strings to number

Strings

var myNum = Number(str);var mySecondNum = +str;var myThirdNum = parseInt(“123mm”) // result in 123var myForthNum = parseInt(“08”) // result in 0var myFifthNum = parseInt(“08”, 10) // result in 8

var myString = num.toString();var mySecondString = String(num);

Page 26: JavaScript for.Net Developers The things you need to know Pavel Kolev

26

String methods charAt charCodeAt compareLocale concat indexOf lastIndexOf localeCompare match replace search

slice split substring toLocaleLowerCase toLocaleUpperCase toLowerCase toString toUpperCase trim length

Page 27: JavaScript for.Net Developers The things you need to know Pavel Kolev

27

Trim

if(typeOf String.prototype.trim !== ‘function’) {String.prorotype.trim = function() {

return this.replace(placeRegExHere);}

}

Page 28: JavaScript for.Net Developers The things you need to know Pavel Kolev

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

Page 29: JavaScript for.Net Developers The things you need to know Pavel Kolev

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;

Page 30: JavaScript for.Net Developers The things you need to know Pavel Kolev

30

Array methods concat every filter forEach indexOf join lastIndexOf map pop push

reduce reduceRight reverce shift slice some splice toLocaleString toString unshift

Page 31: JavaScript for.Net Developers The things you need to know Pavel Kolev

31

Sorting

forEach

Removing items from the array delete splice

Array methodsarr.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

Page 32: JavaScript for.Net Developers The things you need to know Pavel Kolev

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)

Page 33: JavaScript for.Net Developers The things you need to know Pavel Kolev

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’ // truetypeof array === ‘object’ // true but we have

Array.isArray

Page 34: JavaScript for.Net Developers The things you need to know Pavel Kolev

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

Page 35: JavaScript for.Net Developers The things you need to know Pavel Kolev

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;

Page 36: JavaScript for.Net Developers The things you need to know Pavel Kolev

Objectsvar 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 immutableObject.getOwnPropertyNames(obj); // event not

enumerables

Page 37: JavaScript for.Net Developers The things you need to know Pavel Kolev

Coming from C it has all the same operators Arithmetic

+ - * / %

Comparison == != > < >= <=

Logical && || !

Bitwise & | ^ >> >>> <<

Ternary ?:

Operators

Page 38: JavaScript for.Net Developers The things you need to know Pavel Kolev

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”

Page 39: JavaScript for.Net Developers The things you need to know Pavel Kolev

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;

Page 40: JavaScript for.Net Developers The things you need to know Pavel Kolev

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; }

Page 41: JavaScript for.Net Developers The things you need to know Pavel Kolev

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() { … };

Page 42: JavaScript for.Net Developers The things you need to know Pavel Kolev

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

Scope

Page 43: JavaScript for.Net Developers The things you need to know Pavel Kolev

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

Page 44: JavaScript for.Net Developers The things you need to know Pavel Kolev

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

Page 45: JavaScript for.Net Developers The things you need to know Pavel Kolev

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);

Page 46: JavaScript for.Net Developers The things you need to know Pavel Kolev

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

Page 47: JavaScript for.Net Developers The things you need to know Pavel Kolev

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

Page 48: JavaScript for.Net Developers The things you need to know Pavel Kolev

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

Page 49: JavaScript for.Net Developers The things you need to know Pavel Kolev

Pseudoclassical inheritancefunction Human (name) {

this.name = name;}Human.prototype.myFunc = function () { … };

function Student(name) {this.name = name;

}

Student.prototype = new Human();Student.prototype.otherFunc = function() { … };

Page 50: JavaScript for.Net Developers The things you need to know Pavel Kolev

Functional inheritancefunction human (name) {

return {name: name,myFunc: function () { … }

}}

function student(name) {var that = human(name);

that.otherFunc = function() { … };

return that;}

Page 51: JavaScript for.Net Developers The things you need to know Pavel Kolev

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

Page 52: JavaScript for.Net Developers The things you need to know Pavel Kolev

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

Page 53: JavaScript for.Net Developers The things you need to know Pavel Kolev

AJAX2000-2005?

Page 54: JavaScript for.Net Developers The things you need to know Pavel Kolev

The future12.01.2016

Page 55: JavaScript for.Net Developers The things you need to know Pavel Kolev

I believe this presentation is not going to end on time but if you

have any questions… otherwhise contact me

[email protected]://pavelkolev.com