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: , ,
Posted in Programming | No Comments »

Is JavaScript more object-oriented than other programming languages?

Written by shareapost on June 28, 2008 – 4:19 pm -


Like this post? Publish It On Your Own Blog


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:

  1. The form element will display the value of object property (In our case, the value of person.Name)
  2. 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) &amp;&amp; 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.

Download a small example application..


Tags: , , , , ,
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 &lt; 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 »

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 »

Why software projects fail?

Written by Anay on December 9, 2007 – 6:44 am -

Developing of software project is not just a task related to computer programming. Software development involves of lot planning, understanding of requirements, proper design, maintainability and of course, programming. As software planning involves so many tasks, it should be very easy to guess that software projects don’t fail just because of wrong programming, but mostly because, other tasks involved in software development are not handled properly. Recently, I got a chance to review some projects that are being developed in one educational institute in Goa. In this article, I will try to look at some faults that will eventually render these projects useless practically.

Database security: One of the projects developed inside the institute is to get the marks of students and prepare the report of failed students. The application is totally window based program developed in C# which connects to the central database. User need to start the program, login with his username as password, enter the marks for students and create report based on it. Looks like a perfect piece of software. But there is one major security loophole.

Management feels that the software is quite secure as no one can enter or change the marks unless the user logs in with his username and password. The biggest fault being overlooked here is an access to the central DBMS. The connection string required to connect to the central database is stored in a ‘application_name.exe.config’ file which is present in the same folder where application is installed. In other words, this simple text file is installed on every single client machine and any user can read it. Any student can directly login to the central database using the username and password mentioned in the connection string, and can change his marks or delete all records.

This problem could have been easily handled by creating a web service to handle the database tasks and by making the application use this web service. In this way, the connection string would have been in the ‘web.config’ file on the central server and away from any third party access.

Password storage: Care should be taken while user information is stored in the database. User sensitive information should be stored as securely as possible. This is one reason why normally people use MD5 to obtain the hashed password which is then stored in the database. MD5 is one way hash and it is not possible to obtain the original password from hash. People normally keep the same password for different accounts. For example, an user can have same password for his Gmail as well as Yahoo mail account. If the password is stored directly, an administrator having access to yahoo mail’s central database can easily obtain the password of the user and hack his gmail account.

There is another project being developed called inventory management system for the departmental stores. Here, the lead person wants the password not to be hashed but to be encrypted so that it could be retrieved back. Clearly, there is a big security loophole.

Improper use of software development concepts: Software could be programmed either in procedural way or in object oriented way. The program is being written in objected oriented language like C# doesn’t mean that program is object oriented. Program becomes object oriented when the whole program is designed using classes such that there is code reusability along with use of abstraction. Care should be taken that internal structure of class is not exposed. When software is developed in this way, it makes code more maintainable and extendable. Handling of bugs becomes much easier this way.

However, the lead person who is in charge of inventory management system wants the system to be developed neither in procedural nor in object oriented way. He wants to use something that he calls as “Hybrid” way of software development. I have never heard or seen any projects developed in this way. If someone knows, please let me know.

Software programming could be an easy task, but software development is definitely not an easy task. It needs lot of effort to design a software application and plan its development. Care must be taken while developing applications where security is going to play a key role. We should keep our mind open to learn from others mistakes and also from the approach followed by successful software developers. It takes time and hard work to develop a software application and thus, it’s the responsibility of every person involved in the project to develop it properly. Software should be designed to survive and not to fail.


Posted in Programming, Technologies | No Comments »

How to learn computer programming?

Written by Anay on October 13, 2007 – 9:41 am -

I’ve seen lot of people asking questions on exactly what they should do to learn computer programming. Well, there is no single answer for this question as computer programming is more than just learning a programming language like C and Java. I have seen some people recommending books on C/C++ etc. while some people believe that books cannot teach computer programming. In this article, we will see how a person can learn computer programming.

As I have said before, computer programming is lot more than just learning a programming language. Learning a programming language is nothing but learning its syntax and the constructs provided by that particular language. It is like learning different words in English like ‘cat’ or ‘sky’. You cannot speak in English just by knowing different words and their meanings but you also need to focus on grammar. After learning grammar, you actually need to speak in English with other people to get comfortable with it. Learning computer programming is also quite similar.

To learn computer programming, you first need to select a language, which is easier to use and learn. The first computer language that I used was BASIC and then PASCAL. I have seen many people recommending Python these days and I agree with them. Anybody can learn python quickly. However, there are many other languages, which you can use to start with.

After selecting the language, spend some time and go through its syntax and example provided for each. At the same time, try out those examples on your computer to understand how each function or syntax behaves. Keep on practicing until you get comfortable with the language syntax and its use. Before moving on to next steps, make sure that you are very comfortable with the language.

By this time, you will know how to use a language. Keep in mind that knowing how to use a language does not mean that you know computer programming. Computer programming is a way to teach computer how to solve a particular problem. Before learning how to use your language for solving complex problem, you need to learn how to use the language to solve basic problems (like sorting, searching) and how to manage data (data structures).

There are many books available, that will provide you with basic algorithms and will teach you about data structures. Learn those concepts and try to implement them in your language. In this way, after solving lot of examples you will see that most of the problems are solved by using simple concepts. At this stage, you can say that you have learnt computer programming. But wait, that’s not an end. There are many different ways to solve a particular problem and only experience can teach you which one is the best. Therefore, you need to keep practicing.

Remember, that learning computer programming takes lot of time and effort. Its not something that could be learnt directly from books. Even after learning computer programming, you need to practice it regularly with different problems. There are many open source projects, which you will find on the net. You can learn more by looking at their source codes. You can also try to participate in the development so gain more experience.

So keep learning and practicing. That is the way to learn computer programming.


Posted in Programming | 1 Comment »