javascript 101

48
JAVASCRIPT 101 YOGEV AHUVIA www.netcraft.co.il

Upload: ygv2000

Post on 15-Jan-2015

895 views

Category:

Technology


0 download

DESCRIPTION

JavaScript 101 presentation. Goes over the basics of JavaScript language.

TRANSCRIPT

Page 1: JavaScript 101

JAVASCRIPT 101YOGEV AHUVIA

www.netcraft.co.il

Page 2: JavaScript 101

OVERVIEWlet’s talk about the roots

JavaScript

1995

Netscape

Interactivity

HTML

Dynamic

Validations

EffectsAnimations

ClosurePrototype

Ajax

Events

DOM

Performance

Security

jQueryBrowser

Page 3: JavaScript 101

.JS

Developed by Brendan Eich at Netscape

Came to add interactivity to the web

First appeared in Netscape 2.0

Second, Internet Explorer 3.0

Industry standard since 1997

Prototype-Oriented language

Not compiled; interpreted

Version 1.0 released in 1995

Page 4: JavaScript 101

6789

101112131415

Code Exam

pleOVERVIEW

1 var myString = ‘javascript’;

2 var myArray = [1, 2.5, ’3’, [myString, ‘ rules’]];

3 for (var i = 0; i < myArray.length; i++) {var arrayElement = myArray[i];console.log(myArray[i]);

}> 1> 2.5> 3> javascript, rules

Page 5: JavaScript 101

6789

101112131415

Code Exam

pleOVERVIEW

1 function factorial(n) {if (n == 0) {return 1;

}return n * factorial(n - 1);

};

2 var myObject = {myProperty1 : factorial(3),myProperty2 : ‘name’,myProperty3 : {},myProperty4 : function() {alert(‘hello world’);

}};

3 myObject.myProperty4();

Page 6: JavaScript 101

CORE CONCEPTSwhat does it offer?

Page 7: JavaScript 101

• An API for browser documents

• Describes the hierarchy of objects that form a document

• Cross browser and language independent

• Allows adding, removing or updating elements on the model

• Browsers parse HTML into a DOM tree

• Once parsed into objects, each object can be referenced

DOM1

Page 8: JavaScript 101

document

<html>

<body><head>

<h1><a>[href]

“Header”“Click”

<title>

“My Page”

DOM1

Page 9: JavaScript 101

6789

101112131415

1 var element = document.createElement('h1');2 var text = document.createTextNode(‘My Title’);

3 element.appendChild(text);4 document.body.appendChild(element);

My Titlehttp://www.javascript101.com/examples/

Code Exam

pleDOM1

Page 10: JavaScript 101

• Similar to classes in Object-Oriented programming

• Collection of properties (similar to associative array)

• Objects are being cloned, not initialized

• Every object has a (single) prototype

OBJECTS2

Page 11: JavaScript 101

a

<a.prototype properties>

__proto__ a.prototype

__proto__ ...

x 10

...

OBJECTS2

Page 12: JavaScript 101

6789

101112131415

1 var a = {x: 10

};

Code Exam

ple2 a.x += 5;

a[‘x’]; =153

a.__proto__; =Prototype of Object4

a.__proto__.__proto__; =null5

OBJECTS2

Page 13: JavaScript 101

• Simplified concept of Object-Oriented programming

• Mostly always based on dynamically-typed languages

• Objects are created on run-time either from scratch or by cloning

• Variables are not of a certain type, but the values that are stored in them are

PROTOTYPE-ORIENTED3

Page 14: JavaScript 101

PROTOTYPE-ORIENTED3

a

__proto__

x 10

calc <func>

Object.prototype

__proto__

...

null

c

__proto__

y 30

b

__proto__

y 20

Page 15: JavaScript 101

6789

101112131415

1 var a = {x: 10,calculate: function(z) {return this.x + this.y + z;

}};

Code Exam

ple

2 var b = {y: 20,__proto__: a

};

3 var c = {y: 30,__proto__: a

};

4 b.calculate(30);

5 a.calculate(40);

=60

=NaN

PROTOTYPE-ORIENTED3

Page 16: JavaScript 101

• In JavaScript, functions are first class objects, like any other object

• They have properties (as objects)

• Can be assigned, passed as arguments, returned and manipulated

• Reference to a function can be invoked using the () operator

• Can be nested in other functions

• Implements Closure

FUNCTIONS4

Page 17: JavaScript 101

6789

101112131415

1 function MyFunc(a,b){return a*b;

};

Code Exam

ple

3 function MyFunc(a,b,c){var MyInnerFunc = function(param) {a -= param;

};MyInnerFunc(c);return a*b;

};

2 MyFunc(2,3); =6

4 MyFunc(2,3,1); =3

FUNCTIONS4

Page 18: JavaScript 101

• Execute code after specified amount of time

• Time with a reference to a function or anonymous function inline

• Can canceling the timer before time end

• Used for animations, load balancing, validations and timeouts

• Breaks code execution top-down order

TIMING EVENTS5

Page 19: JavaScript 101

6789

101112131415

1 var delay = 3000; // milliseconds Code Exam

ple2 function timedFunc() {

alert(‘It has been ‘+(delay/1000)+‘ seconds...’);};

3 setTimeout(timedFunc, delay);

4 setTimeout(function() {delay = 5000;timedFunc();

}, delay); 3000ms3000ms

5

TIMING EVENTS5

Page 20: JavaScript 101

6789

101112131415

Code Exam

ple1 var counter = 10;

3 function countdown() {if (counter == 0) {clearTimeout(timerHandle);

}console.log(counter);counter--;

}

4 var timerHandle = setInterval(countdown, delay);

2 var delay = 1000;

TIMING EVENTS5

> 10> 9> 8> 7> 6> 5> 4> 3> 2> 1> 0

Page 21: JavaScript 101

• Scope are contexts of variables

• Every object has a link to the scope chain; local first, then parents and finally - global

• Nested functions can use their variables and also their parents

• Closure architecture allows a function to carry its scope to another context

SCOPES6

Page 22: JavaScript 101

parent scope

y

__parent__

20

current scope

z

__parent__

30

global scope

x

__parent__

10

<global properties>

null

SCOPES6

Page 23: JavaScript 101

6789

101112131415

1 var x = 10; // global scope Code Exam

ple2 (function parentScope() {

var y = 20;(function currentScope() {var z = 30;console.log(x+y+z);

})();})();

=60

SCOPES6

Page 24: JavaScript 101

6789

101112131415

Code Exam

ple1 var myNamespace = {};

2 myNamespace.myClass = function(myParam) {this.myMember = myParam;

};

3 myNamespace.myClass.prototype.myFunc = function() {console.log(this.myMember + ‘ world!’);

};

4 var myInstance = new myNamespace.myClass(‘hello’);

5 myInstance.myFunc(); =hello world!

SCOPES6

Page 25: JavaScript 101

• Functions can be nested keeping their original context

• Mostly implemented in scripting languages

• The closured function saves the scope chain of its parent

• Allows functions to access their parent scope variables as they were on the moment they were closured

• Efficient when looping and using delegate function

CLOSURE7

Page 26: JavaScript 101

global scope

x

__parent__

10

<global properties>

null

parent scope

x

__parent__

20

function scope

y

[context].x

30

__parent__

10 20

CLOSURE7

20

Page 27: JavaScript 101

6789

101112131415

1 var x = 20; Code Exam

ple2 function outer() {

var x = 10;return function inner() {console.log(x);

};};

3 var returnedFunction = outer();

4 returnedFunction();

=10

5 function globalFunc() {console.log(x);

};

6 (function(functionArgument) {var x = 10;functionArgument();

})(globalFunc);=20

CLOSURE7

Page 28: JavaScript 101

• Passing functions as arguments for later use

• Allows running a background worker

• Not freezing User Interface

• Keeping original scope

CALLBACKS8

Page 29: JavaScript 101

CALLBACKS8

Page 30: JavaScript 101

• Elements on page can fire events

• Bind JavaScript functions to handle those events

• Respond to specific user actions

• Some events aren’t directly caused by the user (e.g. page load)

EVENTS9

Page 31: JavaScript 101

6789

101112131415

1 var element = document.getElementById(‘myButton’); Code Exam

pleEVENTS9

2 function myButtonClick() {alert(‘myButton was clicked!’);

};

3 element.onclick = myButtonClick;

4 window.onload = function() {var newElem = document.createElement(‘button’);newElem.addEventListener(‘click’, myButtonClick);document.body.appendChild(newElem);

};

Page 32: JavaScript 101

• Asynchronous JavaScript and XML

• Usually being done with XMLHttpRequest object

• Exchange data asynchronously between browser and server

• Update page elements without refreshing the page

• Data is mostly transferred in JSON format

AJAX10

Page 33: JavaScript 101

AJAX10

Page 34: JavaScript 101

6789

101112131415

1 function updatePage(str) {document.getElementById(‘res’).innerHTML = str;

};

Code Exam

pleAJAX10

2 function doAjaxMagic(url) {var self = this;self.xmlHttpReq = new XMLHttpRequest();self.xmlHttpReq.open('GET', url, true);

self.xmlHttpReq.onreadystatechange = function() {if (self.xmlHttpReq.readyState == 4) {updatePage(self.xmlHttpReq.responseText);

}}

};

3 doAjaxMagic(‘http://www.example.com/ajax.html’);

Page 35: JavaScript 101

THE ENGINE BEHINDlet’s showcase the environment

Page 36: JavaScript 101

BrowserBrowser Layout Engine JavaScript Engine

Google Chrome WebKit V8

Mozilla Firefox Gecko SpiderMonkey

Internet Explorer Trident JScript

Apple Safari WebKit JavaScript Core

Opera Presto Carakan

Page 37: JavaScript 101

RENDERING

Page 38: JavaScript 101

• Browsers treat each <script> tag is a separate program

• JavaScript program is parsed and interpreted at run-time

• Modern browsers compile parts of the scripts for performance

• Interpreting can happen on-load or on-demand

• JavaScript engine is contained in the browser layout engine

INTERPRETING

Page 39: JavaScript 101

• Cannot read or write files on the machine (except cookies)

• Cannot interact with frames of a different domain

• Cannot read the user’s history

• Cannot detect user interaction outside the top frame

• JavaScript code cannot be hidden or encrypted

• Minification and Obfuscation

SECURITY

Page 40: JavaScript 101

Performance Factors

Inline method vs calling function 40% 70% 99.9% 20%

Use literals vs instantiate 60% 10% 15% 20%

For loop vs while loop 0% 0% 0% 0%

Cache globals vs uncache globals 70% 40% 2% 0%

No try catch vs try catch 90% 17% 0% 96%

Page 41: JavaScript 101

EXTENSION LIBRARIESwrappers and implementations

Page 42: JavaScript 101

JQUERYsimplify cross-browser scripting of html

Page 43: JavaScript 101

NODE.JShighly scalable web-servers

Page 44: JavaScript 101

HEAVY APPLICATIONSjavascript mvc frameworks

Page 45: JavaScript 101

MOBILE LIBRARIEStouch-optimized web frameworks

Page 46: JavaScript 101

USER INTERFACEinteraction, animations and effects

Page 47: JavaScript 101

FURTHER READINGlearn the basics, then enjoy the advances

Page 48: JavaScript 101

THANK YOUJAVASCRIPT 101