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>
 
 
 
 Posts
Posts
 
 
No comments:
Post a Comment