JavaScript Misunderstood

Preview:

DESCRIPTION

Why JavaScript is the most Misunderstood Language and some of its Best practices.

Citation preview

JavaScript : Misunderstood

Bhavya Siddappawww.bhavyavoice.blogspot.com

Agenda

Introduction Best practices Some cool stuff Conclusions

The world’s most misunderstood language The name

it is originally called LiveScript JavaScript is not a subset of Java nor interpreted

version of Java Too many versions

ECMA committee Bad official specification Bad reputation – broken language?

Lousy implementation: Browsers do suck Implementations of CSS, events, ... broken Language itself is pretty reliable

Blame IE

JavaScript bad parts

Design errors overloading of +, clobbered global

variables, semicolon insertion... 24.88 + 4.35 -> 29.229999999999997 0 0.0 ”0” “0.0” null undefined are all false 0.0 + ”0” -> ”00” No class public private keywords No package keyword either

How does this work anyway?

JavaScript Good parts

Most used scripting language Every browser, many OSes(Windows, Dashboard),

XUL(Mozilla), Flash(ActionScript), Server-side(Phobos, ASP, Rhino), ...

Great for UI-coding Flexible and powerful

OO, functional Closures + Anonymous functions Everything is an object (including functions) Prototype-based inheritance

AJAX makes it a must-know

JavaScript can be used to do good stuff

Agenda

Introduction Best practices Some cool stuff Conclusions

Always use 'var' Keep your scopes straight with var

keyword Global scope Function scopevar i=0; // Global variable

function test() {for (i=0; i<10; i++) {alert("Hello World!");}}test();alert(i); // i is ???

Always use 'var'

Keep your scopes straight with var keyword Global scope Function scope

function test() {for (var i=0; i<10; i++) {alert("Hello World!");}}// i is 10

Pervasive Scope

Result : ???

var x= 9;function foo() {alert(x); var x = 10; alert(x);};foo();

Pervasive Scope

Result: undefined; 10; Expected: 9; 10;

var x= 9;function foo() {alert(x);var x = 10; alert(x);};foo();

Detect Features, Not Browser

if (document.getElementById){ var element =

document.getElementById ('MyId');}else { alert(“ Your Browser lacks the capabilities required to run this script !”); }

Test For an Element's Existence

if ("innerHTML" in document.getElementById("someDiv"))

{

// code that works with innerHTML

}

Don't Make Assumptions

NEVER rely on JavaScript Don't expect JavaScript to be available

but make it a nice-to-have rather than a dependency

Expect other scripts to try to interfere with your functionality and keep the scope of your scripts as secure as possible.

Ex. JavaScript is enabled but is blocked by a firewall or security policy

Don't use with()

Bad

Good

with (document.forms["mainForm"].elements)

{input1.value = "junk";input2.value = "junk";}

var elements =document.forms["mainForm"].elements;elements.input1.value = "junk";elements.input2.value = "junk";

Eval is Evil

Most powerful and possibly most misused method in JavaScript

Like...“swatting a fly with a sledgehammer”

Every time eval() called, compilation occurs

When is it ok? Math expressions, serialization, dynamic loading of code

Release Objects When Done Ex. Initialization Function

var foo = function(){ // code that makes this function workdelete foo;}window.addEventListener('load', foo, false);

Square Bracket Notation

Dot notation: MyObject.property Bracket notation: MyObject[“property”]

MyObject[“value”+i] OK!MyObject.value+i Fail!

Formsdocument.forms["formname"].elements["inputna

me"] OK!document.formname.inputname Bad!

Unobtrusive JavaScript

We separate Presentation (CSS) from Content (XHTML)

We separate Behavior (JS) from Content

Place CSS and JavaScript in separate files

Dynamically add behavior instead of hard-coding

Unobtrusive JavaScript Bad

OK

Good

<a href="JavaScript:alert('You clicked!')">Click Me!</a><a href="#" onclick="alert('You clicked!')">Click Me!</a>

<a href="clicked.html" onclick="alert('You clicked!')">Click Me </a>

var div = document.getElementById('clickMe');div.onclick = new Function("processClick(this)");

<a id=”clickMe” href=”clicked.html”>Click Me!</a>

Use Object Oriented JavaScript Better reusability and organization Allows for dynamic loading of objects Write in a style more familiar to Java

programmers

Object Oriented Examplefunction Cart() {this.items = [];}function Item (id,name,desc,price) {this.id = id;this.name = name;this.desc = desc;this.price = price;}var cart = new Cart();cart.items.push(new Item("id-1","Paper","something you write on",5));cart.items.push(new Item("id-2","Pen", "Something you write with",3));var total = 0;for (var l == 0; l < cart.items.length; l++ ){

total = total + cart.items[l].price;}

Use Object Hierarchies

In JavaScript names may collide In Java we have packages to prevent this

JavaScript does not have packages You can use JavaScript objects to organize

related objects and prevent naming collisions.

Object Hierarchies Example// create the base BLUEPRINTS object if it does not exist.if (!BLUEPRINTS) {var BLUEPRINTS = new Object();}// define Cart under BLUEPRINTSBLUEPRINTS.Cart = function () {this.items = [];this.addItem = function(id, qty) {this.items.push(new Item(id, qty));}function Item (id, qty) {this.id = id;this.qty = qty;}}// create an instance of the cart and add an itemvar cart = new BLUEPRINTS.Cart();cart.addItem("id-1", 5);cart.addItem("id-2", 10);

Use the Prototype Property Use to define shared behavior and to

extend objects The prototype property is a feature of

the JavaScript language

The property is available on all objects

Prototype Property Examplefunction Cart() {this.items = [ ];}function Item (id,name,desc,price)) {this.id = id;this.name = name;this.desc = desc;this.price = price;}//SmartCart extends the Cart object inheriting its properties and adds a total propertyFunction SmartCart() {this.total = 0;}SmartCart.prototype = new Cart();

Object Literals

Object literals are objects defined using braces that contain a set of comma separated key/value pairs, similar to a map in Java

Example {key1: “stringValue”, key2: 2, key3: ['blue',

'yellow'] Object literals can be used as parameters Don't confuse them with JSON, which has

a similar syntax

Reduce the Size of JavaScript File Remove the whitespace and shorten the

name of variables and functions in a file While developing, don't compress so

that debugging is easier When ready to deploy, consider

compressing your JavaScript files Use minimized (compressed) versions

of 3rd party libraries when available Example tool for compression:

ShrinkSafe

Agenda

Introduction Best practices Some cool stuff Conclusions

JSON

Becoming de-facto standard in transferring information for AJAX applications

Allows us to make cross-domain requests if server supports it

Perfect for serializing JavaScript objects

Getters and Setters in JavaScript 1.5Technology Define functions to be invoked when a

property is accessed Transparent to the client

var squareProto = {side: 0,get area() { return this.side * this.side; }};var mySquare = object(squareProto);mySquare.side = 5;

⊳ mySquare.area - > 25

OpenSocial

Common social networking API Write apps that work with any

OpenSocial enable website Develop OpenSocial apps using only

JavaScript, HTML, and CSS

Zembly

Build widgets, applications with JavaScript, HTML and CSS

OpenSocial soon! Now publicly available, go try it out,

win a prize!

Agenda

Introduction Best practices Some cool stuff Conclusions

Conclusions

Take time to learn JavaScript and use best practices

Prototype-based object system with object()

Learn from the masters Let NetBeans help you!

Recommended