Tutorials
Microsoft AJAX
Microsoft AJAX Library - C# and JavaScript Classes
Production-quality C# implementationIn a production-quality C# implementation you may want to implement rows and columns as properties with get and set assessors, rather than public fields. That implementation, however, would make its JavaScript version more complicated than necessary for the purposes of our examples.
The Table class can be easily implemented in JavaScript as shown in the following code snippet, and it would resemble very much its C# version:
After having declared the object, we can instantiate it by using the new operator and use its properties and methods:
There are a few subtle points you need to notice regarding the JavaScript implementation of Table:
You don't declare public members explicitly. You simply need to reference them using this, and assign some value to them; from that point on, they're both declared and defined.
JavaScript allows you to implement most of the design specifications defined in class diagrams, but the implementation can't reflect the specification as accurately as a C# implementation can. For example, the line Table (int rows, int columns) in the diagram in Figure 3-3 refers to the constructor of the class. In JavaScript, as you know, classes as implemented using functions neither have real constructors, nor support specifying data types for their parameters.
When objects are created, each object has its own set of data—to maintain its own state. However, C# and JavaScript are different in that in JavaScript functions are first-class objects. In C#, the "state" is made of the object's fields. The object functionality, as defined by its methods, is the same for all objects of the same type. For example, if you create many objects of the type Table in C#, each object will have its own set of rows and columns, but internally they all use the same copy of the getCellCount() method. In JavaScript, however, functions are treated like any other variable. In other words, creating a new Table object in JavaScript will result not only in creating a new set of rows and columns values, but also in a new copy of the getCellCount() method. Usually, you don't need (or want) this behavior.
In stead of defining member functions ("methods") inside the main function ("class") as shown earlier, you can make references to functions defined outside your main function, like this:
Now, all your Table objects will share the same instance of getCellCount(), which is what you will usually want.
First Page: Microsoft AJAX Library - C# and JavaScript Classes