JavaScript Basics

50 %
50 %
Information about JavaScript Basics
Technology

Published on March 24, 2009

Author: mankz

Source: slideshare.net

Description

Overview of JavaScript

2009 Mats Bryntse

Contents What is JavaScript JavaScript Basics Functions Objects Bad parts Prototype Scope Ajax JSON Debugging Tools Performance Events Error handling Future of JavaScript

What is JavaScript

JavaScript Basics

Functions

Objects

Bad parts

Prototype

Scope

Ajax

JSON

Debugging

Tools

Performance

Events

Error handling

Future of JavaScript

What is JavaScript ECMAScript Current version in browsers is ECMA-262 edition 3, 3.1 to be finalized in December 2009 http://www.ecma-international.org Not tied to web browsers DOM – Document object model API for working with XML/HTML, 3 levels (level 1 became W3C recommendation in October 1998) http://www.w3.org/DOM/ BOM ( Browser object model) navigator, location, screen, XMLHttpRequest, ActiveXObject... No backing standard ECMAScript DOM BOM JavaScript - The worlds most popular programming language..?

ECMAScript

Current version in browsers is ECMA-262 edition 3, 3.1 to be finalized in December 2009

http://www.ecma-international.org

Not tied to web browsers

DOM – Document object model

API for working with XML/HTML, 3 levels (level 1 became W3C recommendation in October 1998)

http://www.w3.org/DOM/

BOM ( Browser object model)

navigator, location, screen, XMLHttpRequest, ActiveXObject...

No backing standard

JavaScript overview JavaScript is a class-free , object-oriented language Dynamic language, you can change any object at any time Prototypal inheritance (inherit from objects) Lamda functions (or ’anonymous’ functions) 5 primitive types: number string boolean null undefined Loosely typed language var a = 2; a === "2" // false a = "2"; // a is now a string a === "2" // true

JavaScript is a class-free , object-oriented language

Dynamic language, you can change any object at any time

Prototypal inheritance (inherit from objects)

Lamda functions (or ’anonymous’ functions)

5 primitive types:

number

string

boolean

null

undefined

Loosely typed language

var a = 2;

a === "2" // false

a = "2"; // a is now a string

a === "2" // true

Functions Functions are first class objects var Cat = function () { // This is called a constructor function this.purr = function() {}; } Create instance: use the new keyword var myCat = new Cat(); typeof(myCat) // ”object”, not very intuitive myCat instanceof Cat // true, instanceof gives the expected answer // Watch out when forgetting the new operator var cat = Cat(); window.purr // window object is now clobbered Function arguments available through arguments function myFunc() { return arguments.length; } myFunc(”a”, ”b”, ”c”); // returns 3

Functions are first class objects

var Cat = function () { // This is called a constructor function

this.purr = function() {};

}

Create instance: use the new keyword

var myCat = new Cat();

typeof(myCat) // ”object”, not very intuitive

myCat instanceof Cat // true, instanceof gives the expected answer

// Watch out when forgetting the new operator

var cat = Cat();

window.purr // window object is now clobbered

Function arguments available through arguments

function myFunc() {

return arguments.length;

}

myFunc(”a”, ”b”, ”c”); // returns 3

Objects and arrays Everything that is not a primitive derives from Object window.toString instanceof Object // = true Objects are associative arrays / hashtables var a = { text : 'test'}; a["text"] == a.text // true Testing for object property ” text” in a // true Enumerating object properties for (var o in window) { console.log(o + ':' + window[o]); } Array basics push : adds an element length concat : join 2 arrays join(string) : string represenation of the array split by the argument slice(start, end) : returns elements between args sort ([function]) : sorts by alphabet or by function supplied as arg pop : extracts last element

Everything that is not a primitive derives from Object

window.toString instanceof Object // = true

Objects are associative arrays / hashtables

var a = { text : 'test'};

a["text"] == a.text // true

Testing for object property

” text” in a // true

Enumerating object properties

for (var o in window) {

console.log(o + ':' + window[o]);

}

Array basics

push : adds an element

length

concat : join 2 arrays

join(string) : string represenation of the array split by the argument

slice(start, end) : returns elements between args

sort ([function]) : sorts by alphabet or by function supplied as arg

pop : extracts last element

Some bad parts Global variables window object is shared by everyone no warning or crash if a variable is overwritten Easy to end-up with ”function soup”, an unmaintainable mess of global objects & functions (MS Virtual Earth) eval & with var o = {}; with (o) { prop = 2; // prop isn’t defined on object o and ends up on the global object } alert(prop); // 2 == & != typeof semi-colon insertion 0.1 + 0.2 == 0.3 // false (IEEE 754 floating point)

Global variables

window object is shared by everyone

no warning or crash if a variable is overwritten

Easy to end-up with ”function soup”, an unmaintainable mess of global objects & functions (MS Virtual Earth)

eval & with

var o = {};

with (o) {

prop = 2; // prop isn’t defined on object o and ends up on the global object

}

alert(prop); // 2

== & !=

typeof

semi-colon insertion

0.1 + 0.2 == 0.3 // false (IEEE 754 floating point)

Prototype Every function has a prototype, a shared object var sword = function() { this.swing = function(){ // Every sword instance will have its own version of swing console.log(”Swing”); }; }; var sword = function() { }; sword.prototype.swing = function(){ // Every sword created will share this function console.log(”Swing”); }; Use hasOwnProperty to distinguish prototype methods from own properties

Every function has a prototype, a shared object

var sword = function() {

this.swing = function(){ // Every sword instance will have its own version of swing

console.log(”Swing”);

};

};

var sword = function() {

};

sword.prototype.swing = function(){ // Every sword created will share this function

console.log(”Swing”);

};

Use hasOwnProperty to distinguish prototype methods from own properties

Execution Scope Scope is the execution context, the this property var obj = { number : 42, showNumber: function () { alert(this.number); } }; obj.showNumber(); // 42 document.body.onclick = obj.showNumber; // clicking the body shows ”undefined” call and apply can bind a new scope to a function var anotherObj = { number : ”blablabla” }; obj.showNumber.call(anotherObj); // ”blablabla” call (scope, arg1, arg2, ...) apply(scope, [arg1, arg2, ...]) Variable scope: function scope, not block scope for(var i = 0; i<5;i++) {} alert(i); // 5

Scope is the execution context, the this property

var obj = {

number : 42,

showNumber: function () {

alert(this.number);

}

};

obj.showNumber(); // 42

document.body.onclick = obj.showNumber; // clicking the body shows ”undefined”

call and apply can bind a new scope to a function

var anotherObj = { number : ”blablabla” };

obj.showNumber.call(anotherObj); // ”blablabla”

call (scope, arg1, arg2, ...) apply(scope, [arg1, arg2, ...])

Variable scope: function scope, not block scope

for(var i = 0; i<5;i++) {}

alert(i); // 5

Asynchronous JavaScript and XML Term coined by Jesse James Garret in 2005 XHR added in IE5 through an ActiveX object All browsers (IE7+) supports the XMLHttpRequest object Cross domain restrictions apply IE8 implements XDomainRequests, (does not send cookies)

Asynchronous JavaScript and XML

Term coined by Jesse James Garret in 2005

XHR added in IE5 through an ActiveX object

All browsers (IE7+) supports the XMLHttpRequest object

Cross domain restrictions apply

IE8 implements XDomainRequests, (does not send cookies)

JSON JavaScript Object Notation Invented by Douglas Crockford of Yahoo The preferred data transfer format of the web More lightweight than XML { ”property” : ”value”} Possible value types: String Number Object Array true false null eval the JSON to get a native JS object, or use a JSON parser. ECMAScript 3.1 will have native support for JSON.parse and JSON.stringify (already in FF3.1)

JavaScript Object Notation

Invented by Douglas Crockford of Yahoo

The preferred data transfer format of the web

More lightweight than XML

{ ”property” : ”value”}

Possible value types:

String

Number

Object

Array

true

false

null

eval the JSON to get a native JS object, or use a JSON parser. ECMAScript 3.1 will have native support for JSON.parse and JSON.stringify (already in FF3.1)

Debugging FireBug for Firefox(Lite for IE) (1.4 adds JSON viewer) Fiddler (if using http://localhost, use http://localhost .) JsonViewer plugin SyntaxViewer plugin IE: Internet Options -> Advanced -> Disable script debugging debugger; attaches a client-side debugger IE8 has a developer toolbar builtin, for previous versions there is IE Developer Toolbar

FireBug for Firefox(Lite for IE) (1.4 adds JSON viewer)

Fiddler (if using http://localhost, use http://localhost .)

JsonViewer plugin

SyntaxViewer plugin

IE: Internet Options -> Advanced -> Disable script debugging

debugger; attaches a client-side debugger

IE8 has a developer toolbar builtin, for previous versions there is IE Developer Toolbar

Tools Validators JsLint JavaScriptLint Minifiers JsMin Dojo ShrinkSafe YUI Compressor Unit testing JsUnit YUI Test Dojo Object Harness Documentation generators JsDoc YUI Doc Secure execution environments ADSafe (Crockford) Caja

Validators

JsLint

JavaScriptLint

Minifiers

JsMin

Dojo ShrinkSafe

YUI Compressor

Unit testing

JsUnit

YUI Test

Dojo Object Harness

Documentation generators

JsDoc

YUI Doc

Secure execution environments

ADSafe (Crockford)

Caja

Performance YUI Exceptional Performance Team Use Yslow plugin to FB If using namespaced objects repeatedly, assign to a local variable first BAD myNS.subNS.obj.prop = 2; myNS.subNS.obj.name = ”Test”; myNS.subNS.obj.index = 2345; BETTER var m = myNS.subNS.obj; m.prop = 2; m.name .... Even if the JavaScript engines ran at infinite speed, web pages would not run noticeably faster. The DOM operations are typically the culprit when it comes to poor performance. Read Steve Souders blog on High performance websites

YUI Exceptional Performance Team

Use Yslow plugin to FB

If using namespaced objects repeatedly, assign to a local variable first

BAD

myNS.subNS.obj.prop = 2;

myNS.subNS.obj.name = ”Test”;

myNS.subNS.obj.index = 2345;

BETTER

var m = myNS.subNS.obj;

m.prop = 2;

m.name ....

Even if the JavaScript engines ran at infinite speed, web pages would not run noticeably faster. The DOM operations are typically the culprit when it comes to poor performance.

Read Steve Souders blog on High performance websites

Events Events handling in the DOM is tricky, browser implementations vary. Using a JS library that normalizes the event object is very helpful Registering events the old fashioned way (DOM level 0) <a href=&quot;http://www.facebook.com” onclick =&quot;return fbs_click(this)&quot;>Facebook</a> element.onclick = function() {} Only one listener can be registered, last listener assigned wins ” Correct” way of doing this W3C : element. addEventListener (’click’, fn, [executeInCapturePhase]) IE : element. attachEvent ('onclick', fn) // flawed (this points to window in fn, useless)

Events handling in the DOM is tricky, browser implementations vary.

Using a JS library that normalizes the event object is very helpful

Registering events the old fashioned way (DOM level 0)

<a href=&quot;http://www.facebook.com” onclick =&quot;return fbs_click(this)&quot;>Facebook</a>

element.onclick = function() {}

Only one listener can be registered, last listener assigned wins

” Correct” way of doing this

W3C : element. addEventListener (’click’, fn, [executeInCapturePhase])

IE : element. attachEvent ('onclick', fn) // flawed (this points to window in fn, useless)

Error handling Exception handling: try/catch/finally Throw an error throw new Error(’Oops’); Use window.onerror (currently only supported by IE & FF) window.onerror = function(message, url, line) { logError(message); return true; // Indicate the error is handled }; function logError(msg, severity) { var img = new Image(); severity = encodeURIComponent(severity || 0); msg = encodeURIComponent(msg); img.src = &quot;CaptureClientError.aspx?severity=&quot; + severity + &quot;&msg=&quot; + msg; }

Exception handling: try/catch/finally

Throw an error

throw new Error(’Oops’);

Use window.onerror (currently only supported by IE & FF)

window.onerror = function(message, url, line) {

logError(message);

return true; // Indicate the error is handled

};

function logError(msg, severity) {

var img = new Image();

severity = encodeURIComponent(severity || 0);

msg = encodeURIComponent(msg);

img.src = &quot;CaptureClientError.aspx?severity=&quot; + severity + &quot;&msg=&quot; + msg;

}

Future of JavaScript ECMAScript 3.1 to be finalized in December. Some parts already implemented in FF3.x Support for getters/setters Object hardening (.seal and .freeze) JSON support

ECMAScript 3.1 to be finalized in December. Some parts already implemented in FF3.x

Support for getters/setters

Object hardening (.seal and .freeze)

JSON support

Questions? [email_address]

[email_address]

Add a comment

Related presentations

Related pages

JavaScript Tutorial - W3Schools Online Web Tutorials

Well organized and easy to understand Web bulding tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, and XML.
Read more

JavaScript Basics - jQuery Fundamentals :: A guide to the ...

You can try running this program by clicking the and it will copy the code to the built-in editor automatically. Once it's there, you can click the button ...
Read more

JavaScript Basics Course - Start Learning at Treehouse for ...

JavaScript is a programming language that drives the web: from front-end user interface design, to backend server-side programming, you'll find JavaScript ...
Read more

Basics : Introduction - JavaScript Tutorial - EchoEcho.Com ...

EchoEcho.Com - Javascript Basics - javascript tutorial ... B efore you start out with more complex javascripts you should understand the basics.
Read more

JavaScript Basics - GitHub Pages

Home Smooth CoffeeScript. Formats Markdown PDF HTML. Overview. JavaScript is a rich and expressive language in its own right. This section covers the basic ...
Read more

JavaScript Basics for Beginners Course - Udacity

JavaScript Basics for Beginners teaches the syntax used by web developers to create interactive and dynamic websites through an online resume project.
Read more

JavaScript Basics | E-Learning mit Lecturio

Lernen Sie flexibel mit dem Video-Kurs "JavaScript Basics" - nutzen Sie jetzt die kostenlose Vorschau bei Lecturio!
Read more

Beginning JavaScript Tutorials - PageResource.com - The ...

JavaScript tutorials which will help you use basic javascripts on your web pages, even beginners. This javascript tutorial section also includes links to ...
Read more

JavaScript Basics Part 1 - HTML Goodies: The Ultimate HTML ...

This new JavaScript Primer is the first in a series of articles by our new author Mark Kahn. This article explains what JavaScript is, and shows you how to ...
Read more

JavaScript basics - Learning the Web | MDN

JavaScript ("JS" for short) is a full-fledged dynamic programming language that, when applied to an HTML document, can provide dynamic interactivity on ...
Read more