Debugging
- Microsoft Script Debugger.
- Firebug Plugin for Firefox.
- If you replace debug object by console object for log, debug, info, warn and error it will gracefully degrade to console.log;
-
debug.group( 'start of group' ); debug.log( a ); //Log debug.debug( b ); //Debug debug.info( c ); //Information debug.warn( d ); //Warning debug.error( e ); //Error debug.groupEnd(); debug.setLevel(0); // Ensure no console logging occurs. We can use this function to specify debug level
In short:
- use console.log in sprintf format.
- use pointers to function in console.log() to print stack trace of the function.
- use timer logging using console.time(“abc”) and console.timeEnd(“abc”);
General
Access Elements:
- GetElementBy.
- GetElementById(Id).
- GetElementsByName(Name).
- GetElementsByTagName(TagName) TagName = * represents all elements. Also use lowercase.
- DomObject.childNodes() gives all child nodes. You can iterate using for-in or use array index. A child node with nodeType = 1 is an element.
Reload a page:
- location.href=”location.href”.
- location.reload();
- histoory.go(0);
JSON
- The object literal notation of JavaScript.
-
var myJSONObject = {key1: value1, key2: value2, key3: [{key4: value4, key5: value5}, {key4: value6, key5: value7}, {key4: value8, key5: value9}, ]};
- myJSONObject.key3 [0].key5 //value5
- var myObject = eval(‘(‘ + myJSONtext + ‘)’);
- var myObject = JSON.parse(myJSONtext, reviver);
JSON versus Eval:
- security issues.
- faster.
JSON does not support cyclic data structures.
- typeof value //To get typeof.
- var myJSONText = JSON.stringify(myObject, replacer);
Object Oriented Programming
- Javscript is a class free object-oriented language that uses prototypal inheritance instead of classical inheritance.
-
function myClass() { //Function definition this.prop =prop1; //Function property this.method = method1; //Function method this.prototype.method = function () {} //Usage of prototype } function method1 () { } var myClassObj = new myClass(); //Object declaration myClassObj.prop=2; //Object property initialized myClass.inherits(myBaseClass1) //Inheritance myClass.swiss(myBaseClass2, fn) //Swiss Inheritance MyClass.newmethod1=function() {} //Class Augmentation myClassObj.newmethod2=function() {} //Object Augmentation
- We can see that a function can simulate an object. This keyword is used to specify that member is part of the function object. In the last line of the example, you can see the object property getting initialized.
- We don’t need copies of member function. It needs to be created only once as in the case of object-oriented language. So, we attach keyword prototype. Prototype is extending to all instances. Like a template. This can be seen the line against the comment Usage of prototype.
- We can keep on providing function definition outside class which can result in name clashes. Two classes cannot have same function name. So we provide definition inside class.
- Also, we can utilize anonymous functions in which case we create function literals leading to closure.
- function.method(“methodname” function(){}) is another way to create a member method.
- To inherit we can use function1.inherits(function2).
- To access a super method we use uber() like this.uber(“functionname”);
- Swiss inheritance means inheriting certain requested methods. This disciplined approach is needed for multiple inheritance to prevent name collisions childfn.swiss(parentfn,method1, method2,…).
- We can augment a class with methods and any present and future object will be augmented with the new method. This is known as class augmentation. Also, we can augment an object known as object augmentation. In this we add a method to an instance created with a new keyword.
- In Parasitic inheritance we create an object in the constructor / function of the parent class and returns the object back after modifying its object methods. This leads to privileged methods.
-
function myClass(value) { var that = new baseClass(value); that.toString = function () {}; //Override the baseClass method return that; }
Events
- Adding events as an attribute to an HTML element is sometimes known as an inline model or inline registration model.
- The approach of assigning a function to an event handler that is an object property is sometimes called the traditional model or traditional registration model.
- To remove the event we write window.onload=null;
- One event handler is allowed for any given event and object.
-
var theEvent = nsEvent ? nsEvent : window.event;
- Most modern browsers, the event proceeds down the stack of elements, each captured in turn. It then bubbles back up (from event clicked to the document), firing the event handlers as it goes.
- Corresponding to addEventListener and removeEventListener in Netscape we have attachEvent and detachEvent.
- Syntax: object.addEventListener(‘event’,eventFunction,boolean); If Boolean is False, Bubble Up.
- Generating Events: focus(), reset(), submit();
Closure and Memory Leaks
- Returning a function literal created as an internal object within another function, and assigning it to a variable in the calling application, is known as closure in JavaScript.
-
function leakMemory() { var el = document.getElementById('el'); var o = { 'el': el }; el.o = o; }
- Accidental closure can create memory leaks as above.
Call Back Functions
- Syntax:
callback_functions(element, index, and array).
- the filter method ensures that elements are not added to any element unless they pass certain criteria.
- The forEach method takes a function that’s then processed against each element.
- Every method runs the callback function against every element in the array until one returns a false value.
- The map method runs the callback function against all the array elements and creates a new array from the results.
- Some method is the opposite of every, in that it runs the callback function against every element until one returns a true value.
Functions
- Declarative/static.
- Dynamic/anonymous (parsed many times).
-
var variable = new Function ("param1", "param2", ... , "paramn", "function body"); //Literal (Parsed only once) var func = (params) { statements; }
- If a function is used within an expression in another statement, it’s an example of a function literal no matter what the expression is.
- functionName.length gives the number of arguments.
Regex
- Regex(str); or var e=/+s/g;
- re.test(str); resultArray = re.exec(str);
- str.match(rgExp); Also saves those in parenthesis.
- str.replace(rgExp,”$2-$1″);
Array
- To access an element, we can use obj.member or obj[index].
- The push method adds an element to the end of an array.
- The pop method removes the items from the end of the array first.
- The shift method removes elements from the top of the array, which does suit our needs.
- The unshift method adds items to the top of an array.
- array.splice(index, howmany, element1, .., elementX).