User:JohnDR/jsmain


 * document.* properties ff vs ie comparison
 * My Library
 * Greasemonkey / HTML notes
 * Benchmark scripts / Examples / Archives


 * Mozilla Developer Reference
 * MSDN DHTML Reference
 * Examples: GM_xmlhttpRequest
 * Others: C-Sharp, Perl,  Tony

= Javascript =

Questions

 * http://www.w3schools.com/htmldom/dom_obj_anchor.asp - Combine with Area+other similar elements (stopped here)

Basic Stuff
 print( new Date.getHours ); print( (new Date).getHours );    // Same as above print( (new Date).getHours );  // Same as above delete variable;                   // removes variable/object
 * Conditional: variablename = (condition) ? value1 : value2;
 * undefined alternative: If var1 is undefined, then var2 will be taken: variablename = var1 || var2;
 * Java Special Characters: \" (put a backslash)
 * You can break up a code line within a text string with a backslash.
 * Add the following in your html:
 * Comments (non nestable): /* ... */ or one liner: //
 * new objects

abc=32;   // this is a number print( (abc.toString).indexOf("2") );    // now indexOf could be used print( String(abc).indexOf("2") );         // String and Number is a built-in function print( Number("32").toString(16) );        // Converts a string to a number, then use toString obj to convert to HEX
 * number to string or vice versa

x = eval('document.form_name.' + strFormControl + '.value'); x = document.form_name[strFormControl].value;                    // Same result as above
 * eval notes: (avoid eval as much as possible)

onscroll = foo;     // A single mouse scroll will call foo hundreds of times. onscroll = function { if(thand) clearTimeout(thand);         // declare thand as local to the object calling this. thand=setTimeout(function {        dv("x"+document.body.scrollTop);     // just change this to foo/function you want to call     }, 500);                                // this is the ms delay }
 * Delayed onevents (e.g. onscroll calls the function several times):


 * Javascript1.5 or later: "const": Declares a variable as constant. It cannot be changed.

var aa=2; function ScopeDemo { var aa = bb = 0;              // bb is a GLOBAL VARIABLE myfunc = function { }       // myfunc is a GLOBAL VARIABLE  (Add a var at the start to make it local); this.test = function { }    // creates a method called test which is a function print(aa);                    // local aa: 0 print(window.aa);             // global aa: 2   << How to access a global variable! } (new ScopeDemo).test;       // Call the test function. Create an anonymous variable internally.
 * Scoping: "var": declares it as a local variable within the function. There is NO block scope in javascript. If declared outside a function, it is considered global.

var x = 1; for(var y=0;y<10;y++) { var x=4;                      // This is NOT local to the block print("local "+x); } print(x); // outputs 4

var x = 1; (function {   for(var y=0;y<10;y++) {     var x=4;                     // This is local to the anonymous function! Use anonymous function to localize variables.     print("local "+x);   } }); print(x); // outputs 1

if(y==undefined) print('true');   // NO error exception if variable is defined later! var y=1;

if(typeof(xy)=='undefined') { };  // Checks if xy is declared or not

ii=33; foo; print(ii);         // 33 (ii==5 is local to foo) function foo { print(ii);       // This is undefined (not 33), even if "var" is defined later. var ii; ii=5; }

if { } else if { } else { }:  else if while(expr) {  break; continue; } do { ... } while(expr); switch(n) { case 1: execute code block 1; break; case 2: execute code block 2; default: code to be exec; }
 * Flow:

onerror=handleErr;                    // will call handleErr upon error function handleErr(msg,url,lineNo) {  // msg is the error string. url is the url. lineNo is the lineNo. .... };
 * Error handling:

try { code; } catch(err) { code; }    // err=="error message" try { code; throw "Err1";              // Throws error } catch(er) { if(er=="Err1") { code; } }  // Once it enters the catch code then it will not go back anymore.

false    false value null     false value undefined false value 0        false value NaN      false value ""       false value
 * Booleans: var aa = new Boolean;

Modulo:    % Assignment: =, +=, -=, *=, /=, >>=, <<=, >>>=, &=, |=, ^= LOGICAL:   &&, ||, ! BITWISE:   &, |, ^ (xor), ~, <<, >>, >>> (unsigned right shift) ==:       ("2"==2)  -> TRUE ===:      ("2"===2) -> FALSE !=:       (3 != '3')   -> FALSE   (the type is converted) !==:      (3 !== '3')  -> TRUE 0xf:      Hex 07:       Octal
 * Operators. https://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference#Operators

Functions & Methods & Macros

 * Macros
 * isff: You don't need this, better use the (a || b) for a more elegant way.

function isff     { return(!document.selection); }      // document.selection only exist in msie function rand(limit) { return( parseInt(Math.random*10000000)%limit ); }  // 0 to (limit-1)

function newelement(elem, id_toadd, newid, innerhtml) {  // innerhtml is optional var newe = document.createElement(elem); newe.id = newid; if(!document.getElementById(id_toadd)) eval("document."+id_toadd+".appendChild(newe)");  // just for the error message document.getElementById(id_toadd).appendChild(newe); if(innerhtml) document.getElementById(newid).innerHTML=innerhtml; // for some unknown reason, msie dont like non-div innerHTML assignments }

function loop {   // infinite loop template for(var ii=cnt=0;ii<10000;ii++, cnt++) {    // cnt is global var here ...code... if _halt; }  print(cnt); setTimeout(loop, 10); } loop;


 * "function": A function is not executed unless it is called. A function declared inside a "block" can only be accessed within the block.

function foo(var1,var2,...,varX) { ....; return(x); } print(foo.length);                  // Returns the number of arguments needed for function foo
 * Functions / arguments (See also tooltip for arguments example)

var abc = function foo {          // Note the empty argument. You could do this if arguments is used. var i=arguments[0];               // Cannot use "for (i in arguments) { }". var j=arguments[1];               // Must check manually if arguments[n]==undefined print(arguments.length);          // The number of arguments } foo;                              // This is error. foo does not exist. Only abc exist.

window.helloworld = function {    // same as "function helloworld { }" declared in the window itself. [Greasemonkey TIP] alert('Hello world!'); gl_abc=23;                        // THIS IS A GLOBAL variable (without var) }

parent.foo;           // Call a foo function declared in the parent frame. Functions across frames are not visible without using "parent". parent.midframe.foo;  // Call a foo function declared in the frame called "midframe", As long as "midframe" is called first. alert(arguments.callee.toString.match(/function (\w+)/)[1]);    // displays the caller function name. // Can also be used to call an anonymous function recursively. e.g arguments.callee(args);

function foo(arg) { }; foo = function(arg) { }; var foo = new Function("arg", "...code...");  // Variable scope only inherits GLOBAL scope for new Function. This is slow bec it is parsed everytime it is called. var foo = function abc(arg) { };              // NOTE: abc is not accessible outside the function.
 * Different ways of assigning a function

objx.func1 = function { }                   // Valid. "function objx.func1 {" is invalid.

print(fun);                          // OK function fun { print("yay"); } print(fun1);                         // NOT OK fun1=function { print("yay"); }

(function(msg) {   alert(msg);    foo=arguments.callee;     // Name (and declare) an anonymous function. foo could be called normally (global). })('yay');                   // anonymous function. Nice way of making a variable local!
 * Anonymous functions / timeout: (useful in one-time window.setTimeout, document.addEventListener, or assigning to event handlers like click or submit.)

window.setTimeout( function { alert('Hello world!') }, 60);       // anonymous function

function object1 { setTimeout("foo",1000);                 // ERROR bec foo doesn't exist after 1 sec setTimeout(function { foo; }, 1000);  // Works OK bec of closure. Thus, use anonymous function during timeout/onevents function foo { alert('Im foo'); }; }

print navigator.appName                // Browser Name print navigator.appVersion             // Browser Version print navigator.userAgent              // Browser useragent print navigator.cookieEnabled          // Returns true if cookies are enabled print navigator.platform               // platform name (Win32) print screen.availHeight               // Monitor useful Height print screen.availWidth                // Monitor useful Width print screen.colorDepth                // Monitor color depth print screen.height                    // Monitor Height print screen.width                     // Monitor width
 * Other stuff / Timeout / History object

var color1=new String("green"); print(color1 instanceof String);       // returns true print(color1 instanceof Object);       // returns true var color2="coral" print(color2 instanceof String);       // returns false (color2 is not a String object)

t_handler=setTimeout('startTime',500); print("Done");  // Call starttime after 500 ms, however, continue with "print("Done")" right away. clearTimeout(t_handler);                                 // clear/stops the timeout

Closure & Memory Leak
function makeAdder(a) {          // classic closure example (Copied from https://developer.mozilla.org/en/docs/A_re-introduction_to_JavaScript#Closures) return( function(b) {       return( a + b );    }); } x = makeAdder(5);                // x is a function! This is a closure example bec "a" in makeAdder still exist during print below. y = makeAdder(20);               // y is a function! print(x(1));                     // returns 6 print(y(2));                     // returns 22
 * Closure and Memory Leaks (This happens during circular reference)

function addHandler {          // This will LEAK memory bec el is caught in the closure of the anonymous function var el = document.getElementById('el'); el.onclick = function { this.style.backgroundColor = 'red';   // "el" exist in the inner function, thus the memory leak. } }

function addHandler {          // This will prevent the memory LEAK! var el = document.getElementById('el'); el.onclick = function { this.style.backgroundColor = 'red'; } el = null;                    // by the time .onclick happens, el is null already! } function addHandler {          // Another solution to prevent memory LEAK! var clickHandler = function { this.style.backgroundColor = 'red'; }   // "el" doesnt exist here (function {       var el = document.getElementById('el');        el.onclick = clickHandler;    }); }

function addHandler(element) {     // Avoiding closure alltogether (more memory efficient). However, it's not encapsulated. element.onclick = clickHandler; } function clickHandler { this.style.backgroundColor = 'blue'; }

// closure example glb=0; function loop(cnt) {                     // cnt is a local variable var vr=40; cnt++; glb++; if(cnt==50) setTimeout(foo1, 200); if(cnt==200) setTimeout(function { print("In anonymous: cnt="+cnt+" glb="+glb+" vr="+vr); }, 200); if(cnt==1000) { print("Done: "+cnt); return; } setTimeout("loop("+cnt+")", 1);       // Need to do this so that timeout threads will work. vr=50;                                // This value of vr is shown in foo1 and anonymous! function foo1 { print("In foo1: cnt="+cnt+" glb="+glb+" vr="+vr); }     // NOTE: if foo1 is moved outside loop then it will error bec cnt is not defined } loop(0); // Output: // In foo1:     cnt=50  glb= 63 vr=50 // In anonymous: cnt=200 glb=211 vr=50 // Done: 1000
 * Another Closure Example (using setTimeout)

DOM related
document.write(" Hello World! ");                 // Writes the whole html text document.getElementById("desc").innerHTML=txt;           // replaces the text inside the element: document.getElementById("myButton").disabled=true        // Disable a document.getElementById("tableid").appendChild(tr_elm);   // Puts tr_elm (TR element) at the bottom of the tableid
 * General: DOM Reference: http://www.w3schools.com/htmldom/dom_reference.asp

var newdiv = document.createElement("div");              // Creates a new element newdiv.appendChild(document.createTextNode("John"));     // Creates a new text newdiv.id="newid224";                                    // Sets the id document.body.appendChild(newdiv);                        // Adds new div element in body

form_element_submit.click;                             // Calls the submit button of a form (type='submit' element)

tbls = document.getElementsByTagName('table');           // get all tables in the document (returns an array) print(tbls[0].className);                              // get the class="..." for the element print(tbls[0].id);                                     // get the id name lgin = document.getElementsByName('login');              // get all the name="..." if (lgin[0]) { lgin[0].value='username'; } if (lgin[0]) { lgin.item(0).value='username'; }          // same as above. just an example. above is a cleaner way. for (i=0;i<tbls.length;i++) { }                          // iterate to all the found elements for (i in tbls) { DO NOT USE }                           // CANNOT use this bec .item, .length, .namedItem will show up

document.getElementById("someID");          // returns the element object document.getElementsByTagName("p");         // returns an array of elements that are document.getElementById('maindiv').getElementsByTagName("p"); // Returns all under id=maindiv

var elm=document.getElementById("someID") elm.firstChild. // First Child Element elm.lastChild. // Last Child Element elm.parentNode.removeChild(elm);  // Remove the elm element

document.documentElement          // Special property, root node document.body                     // Special property, access to the tag

.nodeName                         // nodeName is tag_name/attribute_name/#text (text node)/#document (document node) .nodeValue                        // The text for text nodes, attribute value for attribute node, not available for document or element nodes. .nodeType                         // 1-Element, 2-Attribute, 3-Text, 8-Comment, 9-Document

document.body.bgColor="yellow"    // Changes the bgColor

width = window.innerWidth  || document.body.offsetWidth;   // ff vs msie height = window.innerHeight || document.body.offsetHeight; // ff vs msie currentTopXlocation = document.body.scrollLeft currentTopYlocation = document.body.scrollTop
 * Window height & width. NOTE: msie requires that the script must be run after tag.

|-> Element -> Element    -> Text "My header" Document  |                  ->  Element   (attribute: href) -> Text "My link" |                 |-> Element ->  Element -> Text "My Title"
 * Heirarchy

DOM Tutorial DOM Lesson one Hello world!
 * Relationships
 * Parent - Parent of is . Parent of "Hello world!" is
 * Child - node has one child node: the node.
 * Siblings - and nodes are siblings

Arrays & Hashes
var arr = new Array;    // Javascript Array must have ordinal (0..n) index so that all the methods will work var arr = [];             // Same as "new Array". Do not use Array as a hash! var obj = {};             // New OBJECT. This could be used as hash. Same as "new Object"; print('pop' in arr);      // TRUE, because pop is a method in Array, even if arr is empty. print('pop' in obj);      // FALSE, no method/properties in new object.
 * Array is an Object. Objects are always treated as pointers.

arr[2]=new Array;       // Need to assign "arr[1]=new Array;" as well if arr[1] is also an array. arr[2][8]=32;             // Array of arrays print(arr[2][8]);

var nnn=new Array;      // This allocates memory bec of the "new" nnn=arr;                  // Object assignment is always treated as pointers. The original allocated memory is garbage collected. arr[0]=9; print(nnn[0]);            // result is 9.


 * hash: In Javascript, this is known as object properties.
 * All array object methods dont work with hashes! Array only work with ordinal (0..n) indexes!
 * Hash object is defined here.

grades["ab"]=value;        // You are adding "ab" property to the object grades. grades.ab=value;           // same as above

var mycars = new Array; mycars[0] = "Saab"; mycars[1] = "Volvo"; for (var iary=mycars, item,i=0,ilen=iary.length; (item = iary[i]) || i<ilen; i++) {  // Excellent way of iterating an Array. Equivalent to "foreach $item (@mycars)". Includes empty/falsy items. // Do something with item } for (x in mycars) {                            // equivalent to "for($x=0;$x<=$#mycars;$x++) {" as an Array context document.write(mycars[x] + " ");       // However, any extension to Array will also showup (using Array.prototype). }
 * for in / iterating array or hash

var hh = {}; hh['fred']=95; hh['mike']=96;              // Use this for simple hash (no sorting of keys, etc) for (x in hh) {                               // equivalent to "foreach $x (keys(%hh))" print(hh[x]); } var hh = new hash; hh['fred']=95; hh['mike']=96;       // Use this for has with builtin methods (sortkeys, etc) for (x in hh.$sortkeys) {                   // equivalent to "foreach $x (sort(keys(%hh)))" print(hh[x]); }

function func(ary) { ary[0]=5; } var abc=new Array; abc[0]=8; func(abc); print(abc[0]);    // RESULT is 5
 * Arguments, any changes inside a function affects the caller. This means that arrays are passed via pointers. It's OK to create new array inside a function then return it later.

delete arr[index];             // array delete hh['key_to_delete'];    // hash
 * To remove an element:

if(23 in arr) { } if('methodtocheck' in obj) { } if('keytocheck' in hh) { }            // This is faster compared to hh['keytocheck']==undefined if(hh.$defined('keytocheck')) { }     // this is just readability. it is exactly the same as above. if(hh['aa']==undefined) { }           // another way
 * in (Check if an element in the list)

var aa = ["a","b","c", "d"];                // 1st method var aa = new Array("a","b","c", "d");       // 2nd method var hh = new hash({a:"john",b:{"xx":"cathy","yy":"catherine"},"c":"paul"}); // Hash list constructor
 * List constructor:

for (i in document['body']['style']) { }; for (i in document.body.style) { }; Thus: hh = new hash({"a" : {"bb":"john","cc":"cathy"}}); hh.a.cc === hh['a']['cc']     -> See "avoiding eval" at the basic stuff.
 * The following are equivalent:

Regex and Text Search
var line='abc3defghi'; if(line.match(/(\d+)(\w\w)/)) { print(RegExp.$1); print(RegExp.$2); } else { print("not found"); }
 * Regex: http://www.webreference.com/js/column5/index.html
 * Reference regex characters: https://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:RegExp
 * $1 example, all regex attributes

line='the function foo'; print(line.match(/function (\w+)/)[1]);          // "foo"   (shorthand notation) if("the function foo".match(/function (\w+)/)) // Direct string test

res=line.match(RegExp("function (\\w+)")); print(res[0]);                                   // "function foo" print(res[1]);                                   // "foo" print(res.index);                                // 4 print(res.input);                                // "the function foo"

regex=/function (\w+)/; res=regex.exec("the function foo");            // The "confusing" notation // same result as above

if(line.match(RegExp("(\\d+)"+vr+"(\\w\\w)"))) { }   // using line variable if(RegExp("(\\d+)(\\w\\w)").exec("abc3def")) { }     // direct string
 * For variable:

res=vr.replace(/(\d+)(\w+)/, "$1 $2"); res=vr.replace(RegExp("regex"), "$1 $2"); .indexOf("string_to_search")   -> -1 if not found .myindexOf("string_to_search") -> 0 if not found (Could be used as bool). This is own method. re = new RegExp("(\\d+)(\\w\\w)"); // RegExp is an object. Removing the "new" works as well. However, better use "new" when assigning. arr = re.exec("abc3defghi");      // returns the $0,$1,$2 as an array print(arr);                       // 3de,3,de if(re.test("abcdef")) { }         // This is false
 * For replace: NOTE: .replace will not overwrite the source object.
 * For fast search:
 * As a RegExp object

Object Prototype / this / constructor / watch / inheritance
function employee(name, jobtitle, born) { this.myname=name this.jobtitle=jobtitle this.born=born
 * See also tooltip for a good example of "this.".
 * "this." cannot be used during onevent calls. See "mythis" below.
 * All objects have .prototype. (String, Number, Date, Array, etc) <<< Adds/modifies methods of an object

var mythis=this;                    // This is a good trick to use during onevent calls. var var_age=10;                     // Default value. This variable cannot be accessed outside the object. this.setage=setagefunc;             // This is not an original part of the obj, see arguments. THIS IS A FUNCTION e.g. fred.setage this.getage=function {            // Anonymous function return(var_age+" years"); }

function setagefunc(newage) {       // Cannot access setagefunc from outside. However, this is equivalent to this.setage var_age=newage; return(this.getage);            // See note on next line regarding usage of "this." inside function }

//setagefunc(15);                   // ERROR. this.getage does not exist inside func! However, if you use: "this.setage(15)" then it works ok. }

employee.prototype.salary=1000;       // Extend the object by adding a salary property. (Not inheritance) var fred=new employee("Fred Flintstone","Caveman",1970) print(fred.salary);         // Output is 1000

print(fred.getage);       // 10 years print(fred.setage(40));     // 40 years print(fred.setage);         // returns the function (useless) fred.setage=5;              // Just for illustration. In objects, you don't reassign if it is a function. print(fred.setage);         // 5 print(fred.setage(20));     // ERROR. (fred.age is not a function bec it is assigned to 5.

function obj { this.go = function { print("1st"); }; } v1=new abc; v1.go;         // output is "1st" abc.prototype.go = function { print("2nd"); }; v1.go;         // output is "1st" v2=new obj; v2.go;         // output is "1st"
 * An object's method/property cannot be overridden by .prototype


 * Inheritance (.call/.apply)
 * .apply(this, ary) is the same as .call except that .apply takes in an array as arguments.

// Using the same employee object as above function employee2(name, jobtitle, born, sal) { this.salary=sal;                                   // new property employee.call(this, name, jobtitle, born);         // inherit the employee! // The above could also be written as: (however, it defines a ".base" method which could be eliminated when using .call) // this.base = employee; // this.base(name, jobtitle, born); } var fred=new employee2("Fred","Caveman",1970, 2000) print(fred.salary);         // 2000 print(fred.myname);         // Fred

employee.prototype.location = "Moab";                // employee is extended function employee2(name, jobtitle, born, sal) { this.salary=sal; employee.call(this, name, jobtitle, born);         // inherit the employee, however, the extension is not taken. } var emp1=new employee("Paul","Engr","2005"); var emp2=new employee2("Ron","Acct","2006"); print(emp1.location); print(emp2.location);                                // UNDEFINED! employee does not have .location originally
 * No Multiple Inheritance / Object Extension is not applied during Inheritance

print( employee );           // Prints the function contents print( fred.constructor );   // Prints the function contents (exactly as above. Infact its a pointer). // .constructor is a read only print( fred );               // Outputs "[object Object]"
 * Object constructor (using the above example).

.watch(property, handler_foo);              // watch a property if it changes .unwatch(property);                         // unwatch it function handler_foo(id,oldval,newval) { }   // id is the property name given
 * watch and unwatch

var fred=new employee("Fred","Caveman",1970) fred.watch("myname", function(id,aa,bb) { print("CHANGED! "+id+" = "+aa+" -> " + bb); } ); fred.myname="new name";    // Will display "CHANGED! myname = Fred -> new name"

// Cannot use employee.prototype.watch(...) // .watch can be defined inside the object using "this.watch(....)";

function myobj(arg) { var txt=arg; this.toString = function { return("Mr "+txt); } } aa = new myobj("John"); print(aa);              // .toString is implicitly called vr = aa;                // vr now points to aa, .toString is NOT called vr = aa+"";             // .toString is called. Do this when you are expecting a string. vr = aa-0;              // .toString is called. Do this when you are expecting a number. vr = Number(aa);        // same as vr=aa-0 vr = aa.toString;     // same as vr=aa+""
 * Special .toString method - called when a number or string is expected.

function employee { ...  if(employee.staticvar1==undefined) { employee.staticvar1=1;                          // one-time initialization }                                                 // .staticvar1 doesn't exist in the created objects ...  if(this === window) { }                            // Determine if called as a function (this===window) or as an object (this!=window) ...  // update or use employee.staticvar1 anytime here ... }
 * Static object variables (equivalent to "static" vars inside classes for c#)

(function objx_init {        // objx_init is just a name. This is not accessible.   print("One time init");      // Do one time initialization here
 * Design pattern for objects with static functions / one-time initialization

objx = function {         // Declare the main function/object print("I'm in objx"); }  objx.func1 = function {    // static function print("doing func1"); }  objx;                      // Call objx (if you need to). });

objx; objx; objx.func1;

Javascript vs Perl Syntax comparison / Benchmark numbers
 Javascript                                |   Perl  ==========================================  ========================================= while { break; continue; }                |   while { next; last; } switch(xx) { case nn: code; default: code } |  if(xx==nn) { } elsif(xx==nn2) { } else { } if(typeof(varr)!='undefined') { }          |   if(defined($varr)) { } | var hh={};                 -no methods-    |   my( %hh ); for (i in hh) { }                          |   foreach $i (keys(%hh)) {  } hh['abc']='a'+3;                           |   $hh{'abc'}='a'. 3 ;                                            | var hh=new hash;          -with methods-  |   my( %hh ); for (i in hh.$keys) { }                  |   foreach $i (keys(%hh)) {  } for (i in hh.$sortkeys) { }              |   foreach $i (sort(keys(%hh)) { } if('abc' in hh) { }                         |   if(defined($hh{'abc'})) { } if(hh['abc']!=undefined) { }                |      -same as above- (slower)                                             | var arr=new Array;                          |   my( @arr); for (var i=0,xx; xx=arr[i];i++) { }         |   foreach $xx (@arr) { } for (var i=0,xx; xx=(["a","b","c"])[i];i++) |   foreach $xx (qw(a b c)) { } arr[0]=23;  arr.push(45);                   |   $arr[0]=23; push(@arr, 45);                                             | if(line.match(/reg(ex)/)) { a=RegExp.$1; }  |   if($line=~/reg(ex)/) { $a=$1; } line=line.replace(/(reg)ex/g, "$1");        |   $line=~s/(reg)ex/$1/g; if(line.match(RegExp($yy, "i"))) { }        |   if($line=~/$yy/i) { }                                             |
 * Basic comparison

Javascript                         |   Perl
 * Object comparison

=
========================= | =========================================                                      | function employee(name)                | package employee; {                                     |  employee.static_var=10;              | my $static_var=10; | sub new { |  my ($class, $name)=@_; |  my $self = {}; bless($self, $class); var mythis=this;                    | var var_age = 10;                   |   $self->{var_age} = 10;       # no direct equivalent for perl for local variable within object this.myname=name;                   |   $self->{myname} = $name; print("in constructor");            |   print("in constructor\n"); |  return($self); | } this.setage=function(newage) {       | sub setage { |  my($self, $newage) = @_; var_age=newage;                   |   $self->{var_age} = $newage; var localv;                       |   my $localv; return(var_age);                  |   return($self->{var_age}); }                                   | }                                       |  function foo {                     | sub foo {           # no equivalent for a "private" function in perl |  my($self) = @_; mythis.ary=[];                   |   @{$self->{ary}}=; mythis.ary.push("abc");          |   push(@{$self->{ary}}, "abc");      # array access return("internal function");     |   return("not internal, this is part of object, Can be accessed"); }                                   | }                                       | }                                      | function emp2(n,s,job) {               | package emp2;                # inheritance | use employee;               # The source obj | @ISA = ("employee");        # inherits from Person | use strict; |  ....                       # add the obj_args here | sub new { |  my ($class, $n, $s, $job)=@_;           # 1st arg is always the classname employee.call(this, n);             |   my $self = new employee($n); ...                               |   ... }                                      | } // ========== main file                | #========= var fred=new employee("Fred");        | my $fred = new employee("Fred"); print( fred.setage(30) );             | print $fred->setage(30); print( fred.myname );                 | print $fred->{myname}; // Cannot be done on js             | employee::foo;             # call foo directly |
 * Benchmark Numbers (Edit this section to show more)

=Reference (and External Objects) =
 * Pie object:  http://www.lutanho.net/diagram/pie_object.html
 * Graph object: http://www.codeproject.com/jscript/dhtml_graph.asp
 * All objects have a .toSource method. .toSource represents the source code of an object. Can be used to create a new object (Don't know how?). This does not exist in msie.

Javascript Functions

 * http://www.w3schools.com/jsref/jsref_obj_global.asp

Event Handlers
eg. <body onload="message">....               // Calls javascript function message. Declare message in     <input type="button" onclick="disp_alert" value="Display alert box">      // Button, calls disp_alert document.getElementById('id1').onmousemove = foo;   // NOTE: No arguments!! in ff, event is automatically passed as argument. In msie, need to use window.event;
 * http://www.w3schools.com/jsref/jsref_events.asp
 * Mozilla DOM window reference
 * addEvent function

leftFrame = parent.frames.leftGuy;   // leftGuy is the name of the frame onscroll = keepTogether; function keepTogether{ leftFrame.document.body.scrollTop = document.body.scrollTop; }
 * Code snippet for keeping two vertical frame always in-sync:

String Objects
txt.toUpperCase        // converts to uppercase   (string object)
 * http://www.w3schools.com/jsref/jsref_obj_string.asp

Date Object Reference
var d = new Date;                        // Date or Date will work print(d.getHours); print(d.getDay);    // Get the date/hour print(new Date.getHours);            // Same notation
 * http://www.w3schools.com/jsref/jsref_obj_date.asp

var start = new Date.getTime         // same as std.getHours*60*60*1000 + std.getMinutes*60*1000 + std.getSeconds*1000 + std.getMilliseconds;

Array&Hash Object Reference
e.g. var mycars=new Array("Saab","Volvo","BMW") var mycars=["Saab","Volvo","BMW"]; var myhash=new hash({"a":"Saab","b":"Volvo","c":"BMW"});
 * http://www.w3schools.com/jsref/jsref_obj_array.asp
 * https://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Array
 * Javascript1.6 are hidden in this section
 * All Array Object DOES NOT work with hashes. ie, only numeric ordinal indices work.

newarr=arr.sort     // This will sort arr and assigns newarr=arr as a pointer;
 * Sort routines:

// Numeric sort: (make (a,b) to (b,a) to reverse): function(a,b) { return(Number(a)-Number(b)); }

// case-insensitive sort: (make (a,b) to (b,a) to reverse): function(a,b) { var aa,bb; return((aa=a.toString.toLowerCase)==(bb=b.toString.toLowerCase)?0:(aa<bb?-1:1)); }

// case-sensitive sort (descending). Default sort is ascending case-sensitive. function(b,a) { var aa,bb; return((aa=a.toString)==(bb=b.toString)?0:(aa<bb?-1:1)); }

Math Object Reference
print Math.random      // Random number (Math method) print Math.floor(1.2);
 * http://www.w3schools.com/jsref/jsref_obj_math.asp

Window Object Reference
Put goodie sample here

non-form DOM reference

 * non-form Standard Property


 * non-form DOM Methods