Skip to content

javascript notes

Inline wherever, internal,external file,

1. Immediate: used inside the head tag
2. Deferred: used inside body then it is called deferred,
Wait until all the body elements loaded.
3. Hybrid: Mixed.
Datatypes in javascript:
6 datatypes: Number,String,Object,Boolean,null,undefined.

var x = 100;
By default only object available is windows.
NULL is a value in js.

var a = new Array[2];
var a = new Array[1][2]; //2 d

if you do a[3] if size is 2 then go error will come – arrays can grown and shrink any time.
delete a[2] – it deletes second index.

3 CATEGORIES of object in javascript:
Native – Array,String,Math,Image,Object,Function,Constructor,Option
Host   – window, document,forms,
Userdefined objects

Pixels – collection of byte – rgb and opacity and can be saved in array.
Can prefetch images using images.

Every element of type array can be anything.

Creating objects in javascripts:
var arr = new Array(5); // Not square brackets!.
arr[0] = 100;

typeof keyword gives us the datatype of the variable.
Should always use var keyword.

var x= “abc” //string datatype
x =  new String(“abc”) ; //here x is object.
var z = “des”

But variable do not have properties and methods.
Objects hold certain properties and methods.
Function which are Constructors : Otherwise first letter should be capital.
function test(){}
var customObject = new test(); //object and a new object.

var xyz = new test();//xyz does not have StringValue

Blueprint of an object – when you create a new object – the new property added
is not available to other objects.

this is a keyword in javascript.
If you remove the this from the StringValue then it becomes a local variable.
function test() { this.StringValue=”yes”;}

To attach a method to a class we do the following
function Circle(radius){this.radius=radius; this.getArea=getArea; this.getCircum=getCircum;}

Function within a function.
function Circle(radius)
function getArea(){  var x= 2*radius ;//radius is LOCAL here, last sent to Constructor}
//function getArea(){  var x= 2*this.radius ;//radius is INSTANCE here, last sent to Constructor}
this.radius = radius;
this.getArea = getArea;
Inner functions can access local variables within outer functions.
Local variable and instance variable are segregated per instance variable.

Or we do:
function Circle(){
this.getArea=function(){} // INLINE FUNCTION
Function can be used as : 4 difft ways.
data : as variable information
class definition   : blueprint
method             : associated with an object. has the implicit this.
anonymous function :
Argument            :


Function :Global scope, bound to scope of object – and that object can be in any scope
Method : bound to an object and has an implicit this.

4 invocation ways of Function
method      invocation pattern : name needed
function    invocation pattern : name needed
constructor invocation pattern : name needed
call/apply  invocation pattern : name not needed

By default each function is called in the scope called “call” .
Scopes: global, object scope, call object
Function is a native object. (F caps).
= function literal :  any function created.

function can be created by Function native object.
We call it Function constructor:  smaller syntax.

var myFunc(“para1″,”para2”, “return para1 + para2”);
: this is equal to function myFunc2(){ para1, para2){return para1 + para2;}

every function is converted to object.
For this Function native object: every time 3 different objects are created.
So if you called a normal function 10 times – then only 1 instance of object created.

But Function can be used as blueprint for creating dynamically new functions.
new Fn() //1
Fn()     // Function constructor – optional to use NEW key word – so equal to the first line
function abc(){}  //object gets created – associated with call scope.

//Each function = object we can add methods, properties
Implicit parameters to a function at runtime there are two implicit parameters available
1. this
2. arguments

If function takes 3 param and 2 passed the third is assumed to be undefined
if function takes 5 param and 10 are passed – the function is still executed.

//Unnamed argument: This allows to access all the arguments.
Named argument can be accessed otherwise also with name also.
arguments is an array.length.

for ( z in customers) //for in loop in javascript.

If function is defined multiple times then the last definition is used.

var a = new Object(); //to create an object.
Prototype property is ONLY available to the object CONSTRUCTOR  and not to its objects.
Like available to Circle and not BigCircle or SmallCircle.

Prototype is a property which is of type Object that is why we can keep adding
properties. Even for those object that are created in past – also get these properties and those all in future.

Javascript interpreter.Lexical Scope:
Prototype property cannot change the value of the instance variables.
because prototype – is loaded before constructor is called.

javascript: objects are always passed by reference and never by value.
prototype is an object.

var arr=[ function(){console.debug(“hi”);}, function(){console.debug(“dust”);}];
call arr[0]; //Unable to call function

//Different object
function Car() {
function BMW() {
function Santro() {
var c = new Car();
BMW.prototype    = c;
Santro.prototype = c;

c.color = “green”;
var b = new BMW();
console.debug(“Bmw color is :” + b.color);

Three learnings:
Prototype information added after inheritance recvd by all objects,.
Modification to base Car object recvd by all child objects.
Modification to alternate Car object not impacting other child objects.

Slideshow with image object.
Validate length of the arguments: If type of values not supplied.
Throw error.sum(a,b,c,d); Alert to be displayed.
Account – Saving,Current,DMAT Account
Sax not used – because read only and need to insert nodes in it.
Dom parser used: coz we have to update nodes also.

Document object : its a DOM object.
documentElement: Html element node. deleteElement,appendElement,replaceElement
Child nodes does not count attribute. it only counts child nodes.
nodeValue only holds for text element.

delete property. or array element.
to check if the property belongs to that class.
Object class has a method named hasOwnProperty.
if(c1.hasOwnProperty(“propertyName”)) then delete.

Any object that we create is javascript has a prototypal linkage to the orignal Object property.

navigator.appName, window.ActiveXObject
xmlParser.async=”false” // dont make it asynch.


xmlReq = new window.XMLHttpRequest();
window.ActiveXObject  // xmlReq = new ActiveXObject(“Microsoft.XMLHTTP”);

0 – not initialized
1 – initialized
2 –  ?
3 = response recvd
4 – request complete, onReadyStateChange

xhr.onreadystatechange = handleData.
responseText and responseXML

JSON: Object literal
array [ , , , , ]
object {        }
value : number,string,Object,boolean,null,undefined or Array.

6 error objects: Error, (Name of the error and message of the error); : 6 types : of errors – name of the Constructor
e.message : details
undefined data

Can extend Error – or create custom error throw{name:”Custom” , message:”Message”}

Every Function is having two methods : call and apply.
When you dont know the name of the function.
call and apply both call the function: Difference among two is:

Event handling: Bubble and Capture

new RegExp(“pattern”);

Pattern matching
Position matching ^
Special char matching
Character class match
Repetition matching (5{3}
Alternation and grouping matching (OR and AND)
Back reference matching. ([] and \)
switch will come in the end and apply on the patter
/i ignore case
/gi global search and ignore case
/\d+/g = digit one or more  – all digits are returned
(\[/(-\””\g) – replace above chars
split(/\s *,\s*/) – remove spaces before after , and returns array

For applying regex: String class has 4 methods
match(regex); returns array
replace() , replaces in string
search(regEx) : searches returns index or -1.true.false

test(): a string for pattern match: mostly used method.:equal to using search.
exec() : equal to match as well as split

var pattern = /php/i
pattern.test(“PHP is your friends” ); returns true;

Sample use of the patterns:

Date matching:

Here \1 is BACK REFERENCING to last ().
Upto 9 back references back references can be used in a string
local variable.  variables are not scoped by any block – they are scoped by function

When we call the function : the calling scope can be in some other namespace
the function when declared can be in other namespace.

Definition and execution takes place in the same scope: Lexical scope

Function within function is called nested function.
It has access to the member of the outer function.

Achieve authorized access to property which belongs to outer function.
Closure: Function returns function.
So the inner function has a pointer to the outer function data.
We do it for authorized access to data. This is like private access to the data.

function sayHello(name){
var text = “hello + name;
var sayAlert = function(){alert(text);}
return sayAlert;

Local variables are not copied they are kept by reference. they are still in strack frame
in memory even when outer function exists.

eval : used and it results in closure. in eval you can even create new local variable.
When you use Function it does not create closure.  since objects created every time!.

obj.addEventListener(‘nameofEvent’, referenceToFunction, phase);
obj.attachEvent (‘onclick’ //IE

Phase is a boolean value that can have two values:

Bubbling phase: false : Event happened on child, if not happ, handled by parent, if not handler destroyed by engine/
Capture phase : true  :

Default is true, bubbling event.  that is traditional way.
Capture ?
Event phases: 1,2,3
1: capture phase
2: bubble parent
3: last bubble.

target,relatedTarget,keyCode, ctrkKey,altKey,shiftKey,altKey,
detail,prevValue, nextValue,source
eventObj.cancelable – cance envet after being firest
eventObj.bubbles property : type of event : Capture or bubble

initUIEvent : UI
initMouseEvent : Mouse
initEvent  : Generic?
initMutationEvents : dom tree
Global abatement  : Example

var BMS = {};
var BMS.Bank = new Bank();

No comments yet

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: