Wednesday, January 21, 2009

JavaScript

real power of javascript on the client side is that scipts have access to hierarchy of objects that are based on content of web page.
for example client side java sciprt can access and manipulate each of the images that appear in a document and can communicate and interact with java applet embedded within an HTML document.

basic applications and features:
controlling document appearance and content:
like displaying date and time on web page
Setting the document's properties like bgcolor font etc.
Conditional HTML generation

Controlling browser
Opening windows with specific size.
Opening new tab.
Programmatically write the HTML tags that create any desired frame layout.
History objects allows to move back and forth within user's browsing history.
Displaying messages in status line of browser window.

Interacting with HTML forms
To calculate shipping charges and sales tax on order placed.
validating form data before sending it to server

User interaction and event handling
displaying messages when mouse hover over a hyperlink
pop up a confirmation dialog box when user submits button

Read and writing client state with cookies
Uses cookie to find if user has previously visited the site, registered etc.
Javascript can dynamically generate content using value of cookies.

More features:
Allows image rollover and animation effects
Time stamping on web pages.
Resizing window

Misuse of java script:
malicious web page can use javascript to send data to some third party software/server.

Java script expression can be evaluated using javascript URL pseudoprotocol in browser.
syntax: javascript:
example: javascript:d = new Date(); typeof d;

best way to debug is look at error console of browser or insert alert statement at appropriate places.
Document.write can also be used but it has limitation as it does not work within an event handler.


JavaScript written using 16 bit unicode character set.
each character represented as 2 bytes instead of most commonly used 1 byte standard.
case sensitive to much extent
semicolon can be omitted if each statement is on a separate line.
try to put each statement completely on separate line.

Converting number base or type
toSring(base)===> this will convert variable to String in base notation.
example: binary conversion:
(x).toString(2);

another way to define function:
var square = new Function("x", "return x*x;");
here arguments list and body of arguments is passed as strings to the function.

Objects in javascript have the ability to serve as associative arrays.
example:
image.width
image.height
image["width"]
image["height"]

creating arrays:
var a = new array(1.2, "javascript", true, { x:1, y:3 });
var a new array(10);

Date object:
var now = new Date(); // holds current day and time
now.getDay();

Javascript also provides error object which can be used for throwing and catching errors.
Javascript is untyped language.

if you assign an undeclared variable to some vale then java script will implicitly initialise that variable for you.
no block scope ... variable declared throughout function body.

All divide operation results in floating point numbers.
equality operator == and ===
in case of string comparison operator can be used but all capital letters will be less than lowercase letter.
example: Zoo will be less than aarjksf

in operator for property check
example:
var has_x_coord = "x" in point; //Evaluates to true

similarly instanceof operator...
example:
var d = new Date();
d instanceof Date; // evaluates to true; d was created with Date()

String concatenation and comparison is tricky.
typeof operator is useful in finding the type of object whether number, string or boolean.

Delete operator of java script is not like delete of C++. C++'s delete operator is used to deallocate memory but javascript not require such functioning because of garbage collection.

javascript:void(0) is useful when you dont want to reload your page.

(.) operator example:
document.lastModified
navigator.appName

switch case statement use:

function convert(x) {
switch (typeof x) {
case 'number':
return x.toString(16);
case 'string':
return '"' + x + '"';
case 'boolean':
return x.toString().toUpperCase();
default:
return x.toString()
}
}

try catch finally is more or less similar to what is there in C++ and java.
throw id used to throw exception.
example:
if (x < 0) throw new Error("X must not be negative");
Exceptions propagate through the lexical structure of javaScript method.
If no exception handler is ever found, the exception is treated as an error and is reported to the user.

try {

}
catch (e){
//
}
finally {

}

there is something called scope chain as well. with operator is used to modify this scope chain. This helps in reducing typing.

frames[1].document.forms[0].address.value
to use directly

with(frames[1].document.forms[0]) {
name.value = "";
address.value = "";
email.value = "";
}

or
var form = frames[1].document.forms[0];
form.name.value = "";
form.address.value = "";
form.email.value = "";

for/in combination is also frequently used to iterate over some array or objects.
exmaple:

for(var prop n my_object) {
document.write("name:" + prop + "; value:" + my_object[prop], "
");
}

Function statement is not the only way to define a function. A constructor can also be used to define a function.
Example:
var f = new Function("x", "y", "return x*y");

array can be sorted using array.sort function call.

function can be defined as data, or literals or using constructors.
example:
var operators = new object();
operators["add"] = function(x,y) { return x+y; };
operators["subtract"] = function(x,y) { return x-y; };

function operaot2(op_name, operand1, operand2){
if(operators[op _name] == null) return "unknown operator";
else return operators[op_name](operand1, operand2);
}

Arguments object is highly useful in passing unlimited number of argument to a function. it also provide a callee property. Using this one can find out about callee function as well.

callee property allows unnamed functions to be invoked and executed.
For example:

function(x){
if (x <= 1 ) return 1;
return x*arguments.callee(x-1);
}

expected number of argument can be obtained using length property of function name however actual count of argument can be obtained using Arguments.length argument.


apart from this one can define function own property.
Use: suppose a function wants unique value to be returned on every invocation then it is better to define property specific to function and store the previously returned value in that rather than defining global variable.

uniqueInteger.counter = 0;
function uniqueInteger(){
return uniqueInteger.counter++;
}

apply() and call() function are also somewhat useful.

Objects can be created using new keyword.
Example: creating and setting properties:

var book = new Object();
book.title = "hello motot";
book.chapetr1 = new Object();
book.chapetr1.title = "jeheheh";
book.chapter1.pages = 19;

Enumerating properties: useful while debugging

function DisplayPropertyNames(obj) {
var names = "";
for(var name in obj) names+= name + "\n";
alert(names);
}

function also define prototype properties to save resources in javascript.

String.prototype.endsWith = function(c) {
return (c == this.charAt(this.length-1))
}

var message = "Hello World";
message.endsWith('h');
message.endsWith('d');

prototype provides a sense of inheritence in javscript.

Array:
slice
splice
concat
sort
length
push/pop
shift/unshift
join
reverse

No comments:

Post a Comment