Taking a close look at inheritance and closures in Javascript
Written by Anay on June 30, 2008 – 10:03 am -Let’s play with inheritance and closures in Javascript. Take a look at the following javascript code:
function BaseClass(){
var id=200;
this.Id=function(){
return id;
}
}
function ChildClass(){
var id=500;
}
ChildClass.prototype = new BaseClass();
var childObject=new ChildClass();
In Javascript, inheritance is achieved using prototype. When we try to access any member on Javascript object, it first tries to search for the member within that object. If the member is found, then its accessed otherwise it tries to search for that member in its prototype object.
We make BaseClass the parent class of ChildClass with the following instruction:
ChildClass.prototype = new BaseClass();
Notice that ChildClass does not have a method called ‘Id’. When we make a call to method ‘Id’ on childObject, it will see that ChildClass does not have ‘Id’ method and so will take it from its prototype object which is nothing but the object of BaseClass.
Based on this knowledge, what do you think will be the output of the following instruction?
childObject.Id()
If you think it should be 500, then you are wrong. The correct answer is 200. This happens due to what is known as Closures. According to a tutorial on javascript closures by Morris Johns:
"a closure is the local variables for a function - kept alive after the function has returned"
To understand how this works in our case, let’s try to understand how javascript actually executes a call to the method ‘Id’ on childObject.
As childObject does not have a method called ‘Id’, it takes that method from its prototype and then executes it. You can imagine that Javascript performs the following steps to execute a call to the method ‘Id’ on childObject.
childObject.Id = ChildClass.prototype.Id; childObject.Id();
But does its mean that in Javascript, it’s not possible to override the values from base class/object at all? Well, It is possible by making a small change to our code. Javascript has a keyword called ‘this’. The ‘this’ keyword points to the object in which the method being called is present. For more information on ‘this’ keyword, refer to the article ‘The this keyword’.
In our current code, we are defining a variable using keyword ‘var’ which makes it local to the function in which it is defined. Due to this, closure comes into picture and call to the method ‘Id’ always prints the value from the BaseClass. To solve this problem, we need to refer to the variable ‘id’ using ‘this’ keyword. This will tell our method to use the value from the object in which the method has been placed. In this way, when the method is placed in ChildClass object, it will print the value of ‘id’ from ChildClass and not from BaseClass. Thus, the modified code which allows overriding is given below:
function BaseClass(){
this.id=200;
this.Id=function(){
return this.id;
}
}
function ChildClass(){
this.id=500;
}
ChildClass.prototype = new BaseClass();
var childObject=new ChildClass();
Tags: closures, inheritance, javascript
Posted in Programming | No Comments »
Something useful: A WYSIWYG WordPress theme editor
Written by shareapost on June 29, 2008 – 9:03 am -Here’s an oldie but a goodie. Confounded by trying to track down fancy-looking WordPress themes? Check out this Web-
based theme editor that lets you tweak every nook and cranny of a theme then spit it back to your server to go live. You can add columns, change fonts and backgrounds, even throw in a customizable tag cloud–all with no coding experience required. All you need is a little creativity and some working knowledge of drop-down menus.
While some WordPress themes have excellent built-in support for doing this right from the WordPress dashboard,
many more don’t, and trying to figure out all the little things like text color is made far easier with a WYSIWYG editor than with WordPress’ built-in editing tools.
Advanced users can throw in graphics or design elements they’ve hosted elsewhere on their server (as long
as it’s got a URL to link up to), and when all is said and done each bit of the theme can be grabbed as an individual file to whatever theme you’re currently using. This is an easy way to try out new fonts and colors without making a mess out of your existing style.css file.
Source: Web Development
Posted in Tips | 1 Comment »
Is JavaScript more object-oriented than other programming languages?
Written by shareapost on June 28, 2008 – 4:19 pm -I started my career as a web developer before the dot.com crash. I learnt all about HTML, IIS, ASP, SQL Server and JavaScript. Equipped with the knowledge I built a few dynamic websites and carried my laptop with me to all my interviews and walked out of an interview with a job as a senior web developer. Before .NET existed, creating scalable and maintainable web application was not easy. ASP had a VB scripting engine. It was not scalable and it did its best to glue the web front end design with the backend database access. Most of the middle tier business logic and data access work had to be done using COM. Looking back you couldn’t build an elegant web application without .NET. JavaScript was used a lot in front-end web development mainly for client-side validation, scrolling tickers and special effects. But most developers never took Javascript seriously as a programming language. I know I didn’t but who would have guess that AJAX gave Javascript a more important position in the world of web development. Its power is hidden in the browser!
If you are not a Javascript developer, you will find writing client-side AJAX application in JavaScript a daunting task. That was one of the reasons Microsoft extended Javascript so that the Javascript language more closely resembles .NET languages such as C# and VB.NET. Actually JavaScript is an object-oriented programming language but there are a lot of C# and VB.NET OO type programmers who found coding in JavaScript less palatable.
In fact I read that some argue JavaScript is more object-oriented than C# or VB.NET. In C# and VB.NET, there are objects and classes and an object is an instance of a class but a class does not exist in its own right. In JavaScript, there are no classes. Classes do not exist. Only objects exist in JavaScript. One of the best feature of JavaScript is you can easily extend it. What is your thought on this?
Douglas Crockford shares his knowledge on JavaScript through his article “A Survey of the JavaScript Programming Language” which I think all web developers should read for a more in depth understanding of JavaScript as a programming language.
Here’s what Douglas Crockford say about JavaScript.
1. JavaScript is not Java. Neither is it a subset of Java. JavaScript shares C-family syntax with Java, but at a deeper level it shows greater similarity to the languages Scheme and Self. It is a small language, but it is also a suprisingly powerful and expressive language.
2. It is not a toy language, but a full programming language with many distinctive properties.
3. JavaScript contains a small set of data types. It has the three primitive types boolean, number, and string and the special values null and undefined. Everything else is variations on the object type.
4. Objects can easily be nested inside of other objects, and expressions can reach into the inner objects.
5. Arrays in JavaScript are hashtable objects.
6. Functions in JavaScript look like C functions, except that they are declared with the function keyword instead of a type.
7. Functions which are used to initialize objects are called constructors. The calling sequence for a constructor is slightly different than for ordinary functions.
8. Named variables are defined with the var statement. When used inside of a function, var defines variables with function-scope. The vars are not accessible from outside of the function.
Source: Development
Posted in Programming | No Comments »
Binding HTML Form Fields To Javascript Objects
Written by Anay on May 22, 2008 – 3:42 pm -Consider that I have a object called 'person' with a property called 'Name' which returns me the name of a particular person. I want to assign this object property to a form element such that:
- The form element will display the value of object property (In our case, the value of person.Name)
- If I change the value in form, then it should automatically get assigned to the object property
In C#, it could be done by using the following piece of code:
nameTextBox.DataBindings.Add("Text", person, "Name");
I really like the way DataBinding works and would really like have something like this when I'm working on web applications to bind a object property to input elements in HTML forms. So I decided to write a small javascript that would allow me to bind object properties to form elements. For example, I wanted to write something like this:
<input type="text" object="person" property="firstName" />
Thanks to the power of Javascript and prototype library, I was able to use data binding in html forms using code:
function initializeFormBinding()
{
var formElements = document.getElementsByTagName('input');
$A(formElements).each(function(formElement)
{
Element.extend(formElement);
initializeFormElement(formElement);
});
}
function initializeFormElement(formElement)
{
if (!(formElementHasObjectAttribute(formElement) && formElementHasPropertyAttribute(formElement)))
return;
var objectName = getAttributeValue(formElement,'object');
var propertyName = getAttributeValue(formElement,'property');
window.eval('formElement.value = '+objectName+'.'+propertyName);
window.eval('formElement.onchange=function(){ '+objectName+'.'+propertyName+' = formElement.value; }');
}
function formElementHasObjectAttribute(formElement)
{
return getAttributeValue(formElement,'object')!=null;
}
function formElementHasPropertyAttribute(formElement)
{
return getAttributeValue(formElement,'property')!=null;
}
function getAttributeValue(element, attributeName)
{
return element.readAttribute(attributeName);
}
Lets see how to use this: First, create a javascript object. For example:
var person = {};
person.firstName = '';
person.lastName = '';
person.age = '';
person.country = '';
After that call initializeFormBinding() function using onLoad attribute of body tag. For example:
<body onLoad="javascript:initializeFormBinding();">
Now, in each of your input elements, put the name of the object in 'object' attribute and name of property in 'property' attribute as follows:
<form> First Name: <input type="text" object="person" property="firstName" /><br> Last Name: <input type="text" object="person" property="lastName" /><br> Age: <input type="text" object="person" property="age" /><br> Country: <input type="text" object="person" property="country" /><br> </form>
Thats it.... If you initialize properties of person object, you would see those values in respective form elements. On the other hand, if you modify the value in a particular input element then it would get reflected in the corresponding object property. Anybody is free to use this code in their applications.
Tags: .net, C#, data bindings, databindings, forms, javascript
Posted in Programming | No Comments »
Using JSON in Alfresco WebScripts
Written by Anay on May 8, 2008 – 2:44 pm -In my current project, we are using Alfresco for the content repository and all the extra functionalities required are developed using Webscripts. While working on one functionality, I had to serialize javascript objects to JSON and also deserialize it. For doing this, there is a nice javascript code on Alfresco Wiki for converting the object to JSON and vice versa. But to use it, you need to make some slight modifications to the code. The original code doesn't generate proper JSON code and also has a syntax error in method to obtain the javascript object back from the JSON string. So here is the proper code for handling JSON:
/* json.js (modified 2006-09-07): added support for RHINO (modified 2006-05-02): json.parse, json,stringify added USAGE: var jsObj = JSON.parse(jsonStr); var jsonStr = JSON.stringify(jsObj); */ if (!this.json) { var json = (function () { var m = { 'b': 'b', 't': 't', 'n': 'n', 'f': 'f', 'r': 'r', '"' : '\"', '': '' }, s = { array: function (x) { var a = [], b, f, i, l = x.length, v; for (i = 0; i < l; i += 1) { v = x[i]; f = s[typeof v]; if (f) { v = f(v); if (typeof v == 'string') { a[a.length] = v; b = true; } } } return '['+a.join()+']'; }, 'boolean': function (x) { return String(x); }, 'null': function (x) { return "null"; }, number: function (x) { return isFinite(x) ? String(x) : 'null'; }, object: function (x) { if (x) { if (x instanceof Array) { return s.array(x); } if (x.hashCode) return s.string(+x.toString()); var a = [], b, f, i, v; for (i in x) { v = x[i]; f = s[typeof v]; if (f) { v = f(v); if (typeof v == 'string') { a.push(""+s.string(i)+':'+ v+""); b = true; } } } return '{'+a.join()+'}'; } return 'null'; }, string: function (x) { if (/["x00-x1f]/.test(x)) { x = x.replace(/([x00-x1f\"])/g, function(a, b) { var c = m[b]; if (c) { return c; } c = b.charCodeAt(); return 'u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16); }); } return '"' + x + '"'; } }; return { parse: function(s) { try { return !(/[^,:{}[]0-9.-+Eaeflnr-u nrt]/.test(s.replace(/"(.|[^"])*"/g,""))) && eval('(' + s + ')'); } catch (e) { return false; } }, stringify: s.object }; })(); }
Here is how to use this code to serialize a javascript object:
o={}; o.name = "Name"; o.id = 1; j = json.stringify(o);
Also, to obtain the object back from JSON string, you can use following method:
x = json.parse(j);
Posted in Programming, Technologies | No Comments »
Humorous Video: Agile vs. Waterfall
Written by Anay on March 12, 2008 – 3:52 pm -Many big guys have participated in discussions regarding agile and waterfall model. Hold on big guys, look at this video where two kids have nicely presented the debate on agile vs. waterfall.
Posted in Funny, My Thoughts, Technologies | 3 Comments »
Is it really true that something is better than nothing?
Written by Anay on January 10, 2008 – 7:19 am -They say that something is better than nothing. To some extent even I don’t disagree with this statement. But sometimes, you might end up collecting a lot of that ‘something’ which may not serve your purpose at all. You might end up collecting so much useless information and advice that you will actually feel that actually ‘nothing’ is better than lot of useless ‘something’. When we say that time is important, we should make sure that we save ourselves from these useless ‘something’ and focus on things that we really need.
Being a software application developer, I would like to consider what happens in a typical software industry. What is expected from a software project is nothing but working software. But still, most of companies end up using so called ‘up front’ design approach. In this approach lot of time is spent in designing E-R diagrams or UML diagrams including text documentation. Here, I’m not saying that documentation is useless, but considering the effort that is required to change them once the requirement or design decision is changed, it does feel like a big waste of time. There is another approach in developing software known as Test Driven Development (TDD). In this approach, unit tests are written before the code that implements the required functionality. These tests are written such that:
1. They explain the function of unit under the test
2. The broken functionality is identified automatically as soon as possible
Text based documentation can serve the purpose stated in point 1 but fails to identify broken functionalities automatically. Thus it’s better to have unit tests than to have documentation in text.
Similarly, in case of online forums, threads are created asking for help. But most of the time I see replies like “Yes I agree” or “Wow!!! That was great”. I have seen replies that advice the creator of the thread to search Google for more information. Such replies don’t add any real value to the owner of the thread or to other readers. If you want to give your opinion then make sure that you also add value to the thread by recommending your own solution. This way, every reply to a thread will improve the discussion further.
Another case I would like to consider is the case of websites which are created only to make money. Such websites are known as virtual real estates and use PLR articles as content. This leads to hundreds of websites having similar content floating in cyberspace. Another fact is that, most of the time such websites are created by people who knows nothing about the topic. The articles are mostly ghostwritten or taken from PLR sources or article directories. Google knows that such duplicate content doesn’t add any value to internet users and thus, hides the results containing duplicate information.
Whatever may be the case or purpose, we should remember that whatever we do, even if it’s little, should add value to our work. Something is better than nothing holds true only when that ‘something’ has a value and not otherwise.
Posted in My Thoughts, Programming, Technologies | No Comments »
Active mind and software development
Written by Anay on January 8, 2008 – 7:20 am -Every software developer knows the importance of his or her own mind. Well, I feel that software development itself is an excellent mind game where an active mind can help you to drive the design and development of your software effectively.
If you are involved in the development of software for a domain where requirements keep changing every second, a developer needs to come up with new and new ideas to prevent the development process from stalling. To think of new ideas, you need to keep your mind focused on the problem which is difficult if your mind is not active.
To keep your mind active all the time, you basically need to keep it engaged in some activities so that your mind won’t have to stay idle. Let’s look at some activities that can keep your mind active and engaged for most of the time.
1. Reading: Everybody knows the importance of reading. Apart from keeping your mind engaged, it also helps you to learn new concepts, and to come up with some new ideas. You could read literature on almost any topic. Normally, whenever I get tired after long hours of software development, I like to read some story books or newspaper. It distracts my mind for a short time from the puzzles I was trying to solve while coding and thus, making it fresh again after some time.
2. Writing: Some people think that writing is generally a physical exercise. Just try to write some original articles or essays and you will come to know how much you need to think. But what to write? You can keep your personal diary where you can write your daily experience or a weblog where you can post your thoughts or ideas which could help others. If can even try to write your own poems or songs even if you haven’t written one before.
3. Playing mind games: Games like chess or sudoku are quite challenging by nature. You can even play these games without moving away from your computer (lol). Don’t worry if you are not expert in chess or sudoku as we are trying to play just for the sake of keeping our mind engaged.
4. Observing mother nature: If you are really bored of reading, writing or even playing then you can just hang out in some nice garden and appreciate the beautify of our mother nature. Trust me, it works!!!!! Once when I was struggling to come up with an algorithm to write one game, Alan had advised me to go out and look at birds and trees. I listened to his advice and soon after that, my problem was solved.
Here I’ve mentioned the activities that I follow to keep my mind active. Sometimes, I even do meditation for around 10 minutes. Don’t just limit yourself to these activities for keeping your mind engaged. Do whatever you like but make sure that your mind won’t stay idle.
Posted in My Thoughts, Tips | No Comments »
Professionalism: A misunderstood term
Written by Anay on December 30, 2007 – 9:49 am -Everyday, thousands of students join engineering colleges thinking that they are going to be “Professionals” after completing around four years of course. Once I asked some students the reason behind joining computer engineering in college. One of the answers that I got was “To become professional software developer”. On the other hand, I have noticed students appearing for interviews wearing formal clothes just to show that they are professionals. Not only students, but many times, people working in software companies develop a culture where they won’t call you professional unless you are going to wear formal clothes.
I know these experiences are little funny but they clearly show how people have misunderstood the term “Professional” and “Professionalism”. Once I met one of my friends during office timings and noticed that he was trying to be too serious in his approach. At his home, he used to be pretty humorous. When I asked him about the reason behind his change of behavior, he said he needs to be serious to look professional. So what exactly is professionalism?
While at work, it’s true that you need to follow some dress code and work ethics but that doesn’t mean that being professional is only limited to acting serious and wearing formal clothes. According to an article titled ‘What is a professional programmer?’ by Sarah George, being professional is to have set of qualities like trustworthiness, teamwork, leadership, communication, constant updating of skills, an interest in minimizing risks and accountability.
I completely agree with Sarah George. However, now I have a new question in my mind. Are our professional colleges trying to develop these qualities in students or are they trying to make them pseudo professional by training them with false concepts. When I raised this question in front of related authorities, they simply said it’s the fault of students that they don’t take any interest to learn by themselves.
There are many reasons behind misunderstanding the meaning of professionalism. But it’s our responsibility to leave such misunderstandings behind and develop the qualities described by Sarah George. This will not only help us in developing our career but will also help in the progress of our nation, world and the whole human race.
Posted in Career, My Thoughts | 4 Comments »
Fring with Airtel GPRS
Written by Anay on December 30, 2007 – 6:00 am -Fring is an application for mobile phones that allows you to make calls using VoIP. Yesterday I decided to try it out myself. I had mentioned in one of my post that it is possible to make free calls with fring if you have access to public Wi-Fi hotspots, but in Goa, there are no such public Wi-Fi hotspots. On the other hand, my Nokia N72 doesn’t have support for Wi-Fi networks. So I had to rely on GPRS connection.
If you refer to Fring website, it mentions that the application is compatible with Symbian from version 8 to 9.2. Thus it can work on my Nokia N72. I activated Airtel GPRS service on my handset and downloaded fring directly on my mobile from its site.
After installation, fring asked me to register as a new user. Then, I had to select one VoIP service provider from Skype, MSN Messenger, ICQ, SIP, Google Talk, Twitter, Yahoo and AIM. I have been using skype for long time to make VoIP calls so I selected Skype. After that, fring asked me to login to my skype account with skype screen name and password. That’s it!!!! Now fring was ready for use on my handset.
Fring presented me with list of contacts which were taken from my phone book and skype contact list. From here I could have called my friends who were online on Skype at that point of time. If you try to call a person from your phone book, then you will be presented with options of either Direct GSM call or SkypeOut call.
I wanted to try out fring by making a real call. So I requested my father to call me from skype. Soon, my cell started ringing and Fring showed me that the call is from my father. I was able to talk to my father normally without any problems.
But one thing I noticed is that, I was not able to hear my father’s voice instantaneously. There was a small time gap so I felt as if I’m using a walkie-talkie.
If you want to call your friends at a very cheap rate then should try out fring yourself. Hopefully in near future, just like broadband, the number of public Wi-Fi hotspots in India will increase and then people will be able to use applications like Fring with better voice quality.
Posted in Technologies, Tips | 6 Comments »















