Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Thursday, July 21, 2011

"toString" method in JavaScript


Every object in JavaScript has 'toString' method by default. This method returns the representation of that object in string format. If you have ever called alert on an object in mistake, you would have come across this message in alert box  '[object, Object]'. Actually when you put alert on object itself, it is assumed that you want to see the internal representation of the object and its 'toString' method is invoked which returns the default string for any object as mentioned before.
So what if  you want to make your object representation more meaningful or let say you want to debug your code and just put alert here and there and wants to see what your object looks like at different point of time. Here comes overriding 'toString' method. C#/VB.NET developers, remember yourself overriding toString method of base class "Object". This is exactly similar to that.
Let me take an example as following


function Employee(name, age, company) {
    this.employeeName = name;
    this.age = age;
    this.company = company;
 
    this.toString = function () {
        return "Employee " + this.employeeName + " of age " + this.age + 
" working in " + this.company;
    }
}
What I am doing here is basically forming a meaningful string from my Employee object properties. Now let me put an alert on employee object.

    <script language="javascript" type="text/javascript">
          window.onload = function () {
            var e = new Employee("Abhishek""30""abcSoftware");
            alert(e);
        }
    script>

When I run this code, on my window onload I get following popup.



As I said before, I can use this method for debugging purposes or in general conveying a better representation of my object (for e.g. if you are writing a JS library, you would like your users to get a meaningful message while putting an alert on your objects, won't you?)
Note: If you put alert on function name itself for e.g. alert(Employee), it would be 'toString' method of function type that will be called and it will print your entire function in the alert box. Try that.
Thanks for reading.

Javascript intellisense in Visual Studio 2010


Web developers always found difficult to write code when it comes to writing in any scripting language. There are many reasons contributing to it like lack of debugging features, intellisense support, no early catch on errors etc. If you know what editors like Visual Studio gives you for other contemporary strongly typed language (C#, VB.NET etc) you will find difference of an era.

I am an ardent user of Visual Studio and would like to share with you that there are many good features  that have been bundled with VS 2010 to support intellisense and debugging for JavaScript. If you know them all, you will surely thank Visual Studio team for making your life easy like never before.

Let me explain some of the intellisense support here.

Type inference in JavaScript


JavaScript is a dynamic language and does not support explicit type declarations, due to which, earlier there used to be a generic pop up showing properties for all types. VS2010 can now infer the type as soon as the assignment happens and shows only relevant properties. See the below example, it is showing the properties applicable to a number.





As you know, being a loose typed language, I can change type of any variable at any time. so what if at some point of time i assign a string to my variable "num".


You can see, now VS intellisense shows me properties only relevant to a string. Great, isn't it!!
Kindly note that it does not matter that you are writing inline scripting or inside an external file. Same intellisense works beautifully at all the places.


You can see above, it now shows the properties of a DOM element only.

Intellisense to Functions


Why you have always been asked to decorate your methods with comments during your code review, it is not just to let others understand more about your functions right there but also to give descriptive knowledge to the consumer of your methods about how that method can be called, what purpose that method serve, information about parameters and returning object etc.
By default, VS can show you the name of the function and input parameter if it is put correctly in the scope.

Let say I have written a method "FOO" in my test.js

I included my test.js correctly in my aspx page and now call the method

You can see, without looking at the external file, I know what parameters "foo" expects and can correctly call it.

Wonder, if you could also add some intellisense hint to your method? check this now.

put a summary block under your function as following. this is written exactly the same way, you write it on top of your C#,VB.NET method. so don't need to remember the template, just copy it from any of your C#/VB code page.


and now let me call the method once again and let the magic continue



Getting intellisense amongst external JS files


Do you feel jittery when you need to call a function but don't know how to exact type it and the function is hidden somewhere under the plethora of JS files you are referring in your page (Javascript is case sensitive) or what if you want to make sure you don't write the function with the same name written elsewhere, or just for the sake of simplicity of coding you want everything under the scope (variable, functions etc) visible infront of you before writing even a single line of code as it happens when you write code in C# (you can see every public/protected/internal/private class/methods in the intellisense as per the scope).

There can be many reasons, you always desired intellisense to be available not just inline but also spanning it across external files as well under the scope. Let me tell you it is fairly possible with VS 2010.

Let say I created a new js file and want to reference my test.js (having function FOO, as explained above). What you need to do, just go drag your test.js into your new javascript file. VS automatically add the reference in following manner


Now you have complete access to everything written in test.js to your new file. You can add as many references as you want in  your new file. VS interpreter will automatically discover that file and present you the full intellisense support.





Hope the article would have given you some insight on inbuilt intellisense support of JavaScript in VS. You can explore more on it and be able to write faster code with lesser number of errors.

Happy coding and thanks for reading!


Credit goes to Scott Gu. Reference article: http://weblogs.asp.net/scottgu/archive/2007/06/21/vs-2008-javascript-intellisense.aspx

Thursday, May 27, 2010

javascript parseInt function

There are few internals of parseInt function which you must know before using this function.

  • complete signature of function is parseInt(string,radix). radix is an optional argument which is used as the base of the integer (can be any value from 2 to 36 including) to evaluate your string against
  • if input string starts from any valid number (0-9), parseInt function will return an integer after evaluating against the default base or the base you specified, otherwise will return NaN(not a number) for e.g. parseInt(2abc) will return 2 while parseInt(a2bc) will return Nan
  • If input string starts from 1-9, the default base will be used as 10. if input string starts from 0, the default base used will be 8 (octal). Please note that people assume it to some kind of bug in function when then do parseInt(09) and it returns them value 0.
Please be careful using parseInt function if your input string may start from 0. the best practice is to always specify radix.



good to read: http://www.devguru.com/technologies/ecmascript/quickref/parseint.html

Monday, May 17, 2010

How to debug Javascript & ASP

Writing alert in javascript and Response.Write in ASP to debug has been quite traditional. It just gives you an idea of the variable value runtime, what if
  • You want to frequently change the variable’s value on runtime to do some test
  • You want to step over or step into the function
  • There is a big variant (ASP) or object/Array (Javascript) and you just don’t know its dimension but want to see it all
There could be tons of reasons, you need a good debugging tool. I here tell you some simple tricks to ease your job.
Prerequisite: Microsoft Visual Interdev (comes with Microsoft Visual Studio 6.0)
Debug Javascript: By default, javascript debugging is disabled in browser. To enable it, Open IE, Go to
 Tools -> Internet Options -> Advanced -> Browsing
  1. Uncheck “Disable Script Debugging (Internet Explorer)”
  2. Uncheck “Disable Script Debugging (Other)”
  3. Check “Display a notification about every script error”
  4. Uncheck “Show friendly HTTP Error Messages”
Now whichever line you want to start debugging with in Javascript, just write keyword debugger before that and run your page.
What will happen next: You will be prompted with an error (“A runtime error has been occurred, do you want to debug?”). Now click Yes and choose visual Interdev to debug. You will find interpreter halted on your “debugger” line. Now you can debug it as you debug any other language. Cool Eh!!!
Debug ASP: VBScript is generally preferred as server side language in ASP. Like javascript, vbscript debugging is by default off in IIS. To enable it, Type inetmgr on run prompt, (it will open your IIS (web server) config) Now browse to your app directory under IIS Right click Go To
 Properties -> Configuration -> Debugging
  1. Check “Enable ASP server-side script debugging
  2. Check “Enable ASP client-side script debugging
Now whichever line you want to start with, write keyword stop before that. Now run your page.
What will happen next: You will be prompted with an error (“A runtime error has been occurred, do you want to debug?”). Now click Yes and choose visual Interdev to debug and Bingo!!! You can debug your ASP code like anything.

Inheritance and Polymorphism in Javascript

You must read http://aspnettechstuffs.blogspot.com/2010/05/inheritance-in-javascript.html before going further, I am going to use example from that

creating person class

function Person()
{
    this.eyes = 2;
    this.legs = 2;
    this.color = "white";
}

Inheriting Man class from Person

Man.prototype.constructor = Man; 
Man.prototype = new Person;

writing Man class now

function Man()
{
    this.color = "black";
}

Adding few properties in prototypes directly

Person.prototype.legs = 4;
Man.prototype.legs = 2;
Man.prototype.hair = "black";

creating objects
var p = new Person;
var m = new Man;

The prototype chain for m will look as following

On the same line you can create prototype chain for object p. Now to verify if your objects are actually inherited try following

alert(m instanceof Man);  //will pop up true
alert(m instanceof Person); // will pop up true


Reference: http://mckoss.com/jscript/object.htm

Inheritance in JavaScript

You may know it before that we can implement OOPs concepts in Javascript. I am going to demonstrate here one of them "Inheritance in Javascript".
Before going head let me tell  you some facts about javascript

  1. In javascript every function can be used to create an object out of it with "new" operator. 
  2. Javascript objects are hashed and interpreted that means you can add any property to them on runtime. 
  3. Every function (when used as class) is inherited by an inbuilt function(class) called "prototype" of that function. the constructor of your function/class is implemented inside the prototype of your function/class. So whatever properties or methods you add in prototype would be available to all objects of your function/class by default.
  4. When any property/method is accessed from an object, interpreter first tries to find it inside the object itself, if it is not there then it looks into prototype class of that object and keeps on going up in its prototype chain unless it finds it. the super base of any object is prototype of "object" class itself. If it does not find it after crawling upto "object" prototype then it throws error of "undefined" or "not found".
Now let me give you an example how to implement inheritance

function Person()
{
    this.eyes = 2;
    this.legs = 2;
    this.color = "white";
}

Now I want to derive another class Man out of it
to do so you need to write as following

Man.prototype.constructor = Man; //this line will tell that man object will be instantiated from its own prototype
Man.prototype = new Person;  //this line will  hook Person into Man's prototype chain

Please note that you have to write the above two lines before creating Man class

now I am writing a "Man" class

function Man()
{
    this.color = "black";
}

just to explain you how you can add some properties/methods in objects prototype directly, you can refer following example

Person.prototype.legs = 4;
Man.prototype.legs = 2;
Man.prototype.hair = "black";

Ok, now I am going to create an object of Man class

var m = new Man(); //m is an  object of Man

alert(m.color); // the interpreter will look into class Man first and will popup black
alert(Man.prototype.color); // since prototype of Man does not contain color property, it will move up the prototype chain and will look into Person prototype and popup "white"
alert(m.legs); //legs are not defined in object "m", it will look ito prototype of "m" and will pop up 2


I hope you must have understood by now how this whole inheritance is going to work. This is not different than how you find it working in C#/VB.Net or any other language.