javascript misunderstood

34
JavaScript : Misunderstood Bhavya Siddappa www.bhavyavoice.blogspot.com

Upload: bhavya-siddappa

Post on 10-May-2015

2.664 views

Category:

Technology


1 download

DESCRIPTION

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

TRANSCRIPT

Page 1: JavaScript Misunderstood

JavaScript : Misunderstood

Bhavya Siddappawww.bhavyavoice.blogspot.com

Page 2: JavaScript Misunderstood

Agenda

Introduction Best practices Some cool stuff Conclusions

Page 3: JavaScript Misunderstood

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

Page 4: JavaScript Misunderstood

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?

Page 5: JavaScript Misunderstood

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

Page 6: JavaScript Misunderstood

Agenda

Introduction Best practices Some cool stuff Conclusions

Page 7: JavaScript Misunderstood

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 ???

Page 8: JavaScript Misunderstood

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

Page 9: JavaScript Misunderstood

Pervasive Scope

Result : ???

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

Page 10: JavaScript Misunderstood

Pervasive Scope

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

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

Page 11: JavaScript Misunderstood

Detect Features, Not Browser

if (document.getElementById){ var element =

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

Page 12: JavaScript Misunderstood

Test For an Element's Existence

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

{

// code that works with innerHTML

}

Page 13: JavaScript Misunderstood

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

Page 14: JavaScript Misunderstood

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

Page 15: JavaScript Misunderstood

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

Page 16: JavaScript Misunderstood

Release Objects When Done Ex. Initialization Function

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

Page 17: JavaScript Misunderstood

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!

Page 18: JavaScript Misunderstood

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

Page 19: JavaScript Misunderstood

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>

Page 20: JavaScript Misunderstood

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

programmers

Page 21: JavaScript Misunderstood

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

Page 22: JavaScript Misunderstood

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.

Page 23: JavaScript Misunderstood

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

Page 24: JavaScript Misunderstood

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

Page 25: JavaScript Misunderstood

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

Page 26: JavaScript Misunderstood

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

Page 27: JavaScript Misunderstood

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

Page 28: JavaScript Misunderstood

Agenda

Introduction Best practices Some cool stuff Conclusions

Page 29: JavaScript Misunderstood

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

Page 30: JavaScript Misunderstood

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

Page 31: JavaScript Misunderstood

OpenSocial

Common social networking API Write apps that work with any

OpenSocial enable website Develop OpenSocial apps using only

JavaScript, HTML, and CSS

Page 32: JavaScript Misunderstood

Zembly

Build widgets, applications with JavaScript, HTML and CSS

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

win a prize!

Page 33: JavaScript Misunderstood

Agenda

Introduction Best practices Some cool stuff Conclusions

Page 34: JavaScript Misunderstood

Conclusions

Take time to learn JavaScript and use best practices

Prototype-based object system with object()

Learn from the masters Let NetBeans help you!