Urban pro

View My Profile

Wednesday, May 23, 2012

STEPPING INTO JS OOPS - CHAPTER 2

Hi Friends,

In this chapter we are going to delve deeper into inheritance and objects. I will suggest you here that you install firebug for your mozilla . Because a lot of this will be done using firebug script editor and console .

If you have mozilla 3.0 uptill 8.0 , i suggest you use firebug 1.7.3 xpi .

Install it from this link :  http://getfirebug.com/releases/firebug/1.7/



If you have mozilla 9 and above , i suggest you download firebug 1.8 xpi .

These are the most stable versions of firebugs  for the above versions of mozilla.

Now, Let's get started , shall we ?

I WILL INHERIT MY DAD'S  PROPERTY (Probably) :

Suppose I have an object 'x'  and it inherits all the properties of the object 'y', then in this jargon we shall say that y is the prototype of the object x and  the properties of x override the properties of  y .

I know, i know ... you are going to say what every one else said to me : "I DON'T BELIEVE  YOU" .

Well, what if i give you live examples here .

Inside the script - editor of firebug :

var alpha = {firstName: 'Kunal', lastName: 'Bhowmick'} ;
var beta = {firstName: 'Anirban'};
beta.__proto__ = alpha ; // Making beta inherit everything from alpha

beta.lastName; // O/P : Bhowmick--> in the console .

Whoa, what is this ??
Well, this is actually nothing but inheritance at it's mischievous best .

alpha is my JavaScript variable which contains firstName and lastName .
beta ,however, consists of only the firstName.

Now , to make alpha the parent of beta, we have used  '__proto__'. This is like the 'extends' keyword used in java .

Hence beta.lastName takes the lastName of alpha since it does not have a last name of it's own.
Still, you don't believe me , do yah ?
If so, then have a look at the screen shot below :

EDITOR :



CONSOLE :



 But what happens , when you try to print the firstName of beta :

beta.firstName;
O/P : Anirban

This is because, the properties of the child , present in the child overrides that of the parent .

What if we introduce last name for beta :

beta.lastName = 'Bhattacharjee';
beta.lastName;
O/P : Bhattacharjee

So , it again overrides its parent alpha .

Let's delete the lastName of beta :

delete beta.lastName;
beta.lastName;

O/P : Bhowmick

Since, we have deleted the last name of beta, it inherits the last name of alpha again.

Now, what if try to find the prototype of alpha, the parent .
Ok, so let's have :

alpha.__proto__;

This gives the output as :
This in actuality represents the object Object.prototype --> which is the godfather of all objects .




I HAVE GOT  BAD  NEWS  AND BAD NEWS :




Well, the problem is __proto__ cannot be used in internet explorer and some other browsers because it is not in the ECMA script specification .


But, hang on, before you guys curse my head off, let me tell you that, even though it cannot be used in those browsers, it does not mean that it does not exist there . It is still there, however we deal with it in a roundabout way .


So that is prototype inheritance in a nutshell. 
That is why, though java script does not contain classes, yet still it uses inheritance in this way and hence it is an OOP construct.


HOW DOES THIS INHERITANCE WORK :

 


Alright, alright i am getting into it . 
Have  a  little patience, yea of little faith .


Let us describe an ordinary function :

function Apple(name){ 
    this.name = name;  
}



var apple1 = new Apple('White Apple'); // create an object for Apple


Apple.prototype.greet = function(){
    console.log('Eat me, I am a : ' + this.name);
}


As a result of this, Apple.prototype becomes the prototype of each object that's created via new Apple() such as : apple1 .


So, we have used this prototype to define the function greet() and we will call it in this way :


apple1.greet();


O/P : Eat me, I am a : White Apple

In this way , we can create any number of  methods like greet() and they will be available for all the instances  of the apple object created there of .


This is exactly how, inheritance is used  in java script .


Hope you enjoyed this one .


Good bye .


LEAKING GLOBAL VARIABLE IN JAVASCRIPT

Hi Friends ,

This post is about a very common mistake that is made by the JS programmers who are caught unaware of what they are trying to accomplish.

The most common mistake with a java script variable  is sometimes programmers use them as global variables and as such their values persist for the entire program and does not work the way it is supposed to .


Yesterday, while i was working with a piece of JS code , i encountered this problem .

I had this piece of code :

function FUNC()
{
   K = 100;
}

FUNC();

console.log("K is :" +K); // O/P : 100

But the expected output is undefined since the variable 'K' is a local variable and hence must not be visible else where except the method where it is used .

This is the screen shot that came up in my console :

Now this is called accidental leaking of global variable .
I wanted to have my variable K as a local variable but i have used it as a global variable.
Hence , all this fuss .

So , the important thing that needs to be done is, if we intend to use a variable as a local variable , then we must use the 'var' statement .


function FUNC()
{
  var  K = 100;

}


FUNC();



console.log("K is :" +K);

As a result, this is what i got :


And this is the correct and expected result.

This small mistake messed up my application big time . So remember to use VAR in such cases.

Goodbye,

Have a good day .



STEPPING INTO PYTHON - CHAPTER 1

Hi friends,

This is the first chapter in the stepping into python series. This series will be updated from point of view of the beginners and gradually more advanced features will be published .
So without any further ado, let us delve into the language at hand .

 How to install Python :

FOR WINDOWS USERS : There are a lot of  python interpreters available. Download them and get started. However i vehemently oppose it. Python is a free software available in Linux. So download any flavor of Linux and  get started(My personal favorite is Ubuntu).

FOR LINUX USERS : Just type python in your shell and the interactive mode opens and you are good to go .

OOP : Python is an object oriented language and any variable that you use here acts as an individual object .

SOME IMPORTANT TID BITS :
                                                     help(obj) --> this gives you info on the object
                                                     dir(obj)   --> this gives you the internal structure of the object being used .

BASIC VARIABLES :

INTEGER : An integer is defined in this way :
                   kint = 8
FLOATING POINT NUMBER : kfloat = 7.0

STRINGS : When it comes to strings, you can use single quotes and double quotes both .
kstring = 'kunal'  //valid
    or
kstring = "kunal" //valid

Note double quotes are useful when you are using a string with a single quote in it .

kstring = 'kunal's not home .' // Not valid

This is not valid because the single quote which is there at the beginning of the string in 'k'  ends when it  encounters the single quote after 'l' , hence you have another single quote after stop(.) which is unaccounted for and hence the termination of the string will take place at a time much before than actually expected .

So we use double quotes in such situations :

kstring = "kunal's not home ." // valid

Concatenation  and simple operation is very easy in python :

five = 5
ten = 10

fifteen = five + ten


Hi = "hi"

Ganesh = "ganesh"
HiGanesh =Hi + Ganesh

ASSIGNMENTS :

Assignment can be done in more than one variable and in the same line .

a=2,b=3

BEWARE :

But  for all this cool tricks, do not forget one important thing .
DON'T MIX YOUR OPERATORS OR IT WILL BE THE DEATH OF YOU .

print  five + Hi  // Not Valid --> don't try to concatenate a number with a string .

That is all for today, next we will be looking into chapter 2 of this series which will deal with lists and operators .

Goodbye to you,

All the free thinking souls .


Monday, May 21, 2012

Java Script Error : Error: Expected 'j'


Java Script Error : Error: Expected 'j' :

Hi friends,

Here i am again with another piece of error that i encountered while scripting in java script .

Once I was using an alert and I got this error :  Error: Expected 'j' .

My alert statement was :

alert("Don't  skip but read the whole paragraph .");

Reason : This happened because, the apostrophe is a special character and as such to treat it as a normal character we need to escape it using back slash --> "\" .

So, the alert was re written as :

alert("Don\'t  skip but read the whole paragraph  .");

And voila, it started working properly .

Goodbye .
Have a nice day .

Sunday, May 20, 2012

Stepping into JS OOPS - Chapter 1

I was asked yesterday by my friend : why Java Script supports OOP (Object Oriented Programming).

I told him, it is because Java Script  can use inheritance and  objects .

His next Question was : How so ?

So let us see how java script is related to OOP .

JS (java script) can use Objects and objects are very important because they have attributes which can be used

As in java , we can create objects with the new operator.

CREATING OBJECTS :

Inside script-tag :

kObject = new Object(); // creating objects with new operator

kObject.name = "kunal"; //using object attribute name

End of script-tag .

CONSTRUCTOR :

Java uses constructors . Similarly JS can also use constructors .
Inside script-tag :

fruit : function(name) // My function name is fruit, which can have a name and color as its attribute
{
   this.name = name;
   this.typeOfFruit = function();
{
console.log("This is an" +this.name); // console.log is my favorite way of printing a //statement, it is like println() of java and is used in firebug console. you can also use //alert() here .
}
}


fruit1 = new fruit("Apple");
fruit1.typeOfFruit(); // O/P: This is an Apple


End of script-tag .

Here, the method fruit is an object constructor with its own set of attributes and functions.
Objects for this object constructor can be written using the "new" keyword .
Here we did so and inserted the string parameter Apple and then called the function typeOfFruit(), which in turn gets passed on to the function fruit and we get the o/p : This is an Apple.

WHAT  IS THIS ? : 

A lot of times I have been asked : why do we use this inside a  constructor ?

Here let me  take help of Java to explain this :

Consider a  class rectangle. It has its own attributes like height and width .

public  class Rectangle
{
int height = 10;
int width =    5;

// Now here comes my constructor :

public Rectangle(int Height, int Width)
{

 height = Height;
 width = Width;






/* I can describe my constructor in this way as well :


public Rectangle(int height, int width)
{

 this.height = height;
 this.width = width ;




*/
 
}

You can see that I have used the this keyword in my second description of constructor Rectangle.
The first argument of my constructor is height. 
Inside the constructor, a local copy of the same argument needs to be created. 
Hence , we use the keyword this to point to  the field : height .
If i would have used :
height = height ;
I would have got a warning that : this assignment does nothing.
Because we need to assign the variable : height in the constructor to the class attribute : height .

If we are to think of a real time example , consider that you have a very cool looking laptop. But your friend does not know that this laptop is yours . So what do you do ?

You tell him , in front of your dad that , this laptop is yours and he cannot have it .
Here your dad is the class, you are the constructor , who has the object laptop and you want to make sure that you assign it to yourself .


 
 

 


Saturday, May 19, 2012

Firebug Error --> Variable out of range

Hello friends,

I have thought of sharing this very important piece of info with you guys today .

Its mainly about this error which you might get while debugging  your web application in Firebug in mozilla :

"Varibale out of range (30 of 292)" or something like that.

Do understand that it is mainly because your variable is getting called somewhere else before its actual place where it must be called.

This mainly happens in a scenario where you have getters and setters for this variable and you are returning a value.

In such a case, let me give an example here :

var kVaraiable; // my variable

get kVariable();
set kVariable()
{
    return something;
}

Here , if you see kVariable out of range, then go ahead and take a peek in your firebug console and give special notice to the response and JSON part. You will see that some variable is giving an undefined value there.

Hence, to fix this you need to prevent the setter from returning anything , so you do this :

set kVariable()
{
    if(kVariable != undefined)  // this will prevent the variable from returning anything if it gets called          unexpectedly .
    return something;

}


ADIOS Freinds,
Think Free .


Difference Between Normal Java script and OOP Java Script


Hi friends,

I am sure many of us have troubles differentiating between these two. Well not to fear , in the coming days i will share some info that will shed light on both these two things, which will help us in understanding which is what.

But first,  let me give a simple example of both of them to clear doubts about these two from the mind of us, who are still new bees.



NORMAL JAVASCRIPT :
I know, many of you know how to write normal java script.
For those who are unaware of this , it is written in your html in this way :


Your normal script-tag goes here where you call your function , let us assume you do this in this way :
(button) onclick = callfunction();



//Then add your function :
callfunction()
{
//Do your operation
}

OOPS JAVASCRIPT :
Now the structural flow of a oops java script is very similar to your normal flow of a java program.

Here you have a class and its objects.
There is a syntactical difference also with normal javascript :


Your normal script-tag goes here where you call your function , let us assume you do this in this way :
(button) onclick = callfunction();


//your function call syntax will be a little different here :
callfunction : function()
{
//Do your operation
}

Hence you see the function is added as:

functionName : function(your parameters)
{

}

This is the end of article 1.

Be sure to visit my blog later so that you can see article 2 in detail and other interesting tips and techniques .