For the past eight(8) years Schalk Neethling has been working as a freelance developer under the pseudo of Volume4 and is now the president of Overt Strategy Consulting. During this period he has completed over 300 projects ranging from full web application development to complete branding. As president and lead developer of Overt Strategy Consulting, Schalk Neethling and his team has released a 100% Java standards based content management system called AlliedBridge and business document exchange and review system, called Doc-Central. Schalk Neethling is also actively involved on a daily basis in the open source, web standards and accessibility areas and is a current active member of the Web Standards Group. Schalk is also the co-founder and president of the non-profit The South Web Standards and Accessibility Group, which aims to actively educate and raise awareness of web standards and accessibility to both the developer society as well as business large and small. Schalk also has a long relationship with DZone and is currently zone leader for both the web builder, css.dzone.com, as well as the .NET zone, dotnet.dzone.com, and you can find a lot of his writing there as well as on his blog located at schalkneethling.alliedbridge.com. Schalk is constantly expanding on his knowledge of various aspects of technology and loves to stay in touch with the latest happenings. For Schalk web development and the internet is not just a job, it is a love, a passion and a life style. Schalk has posted 173 posts at DZone. View Full User Profile

Object Oriented Programming with JavaScript

06.07.2008
| 5318 views |
  • submit to reddit

I’ve wanted to move towards programming in C# for a while, and it seems like Silverlight 2 is giving me a great reason to make the time to learn it. In the meantime, in preparation for working with objected-oriented programming (it’s been a while since I did C++), I’ve started trying to shift my JavaScript habits towards an OO format in order to ease my transition.

NOTE: The project files included for this entry use the Silverlight 2 runtime, so you will need to have that installed on your system. The example code itself is still in JavaScript.

I’ve wanted to move towards programming in C# for a while, and it seems like Silverlight 2 is giving me a great reason to make the time to learn it. In the meantime, in preparation for working with objected-oriented programming (it’s been a while since I did C++), I’ve started trying to shift my JavaScript habits towards an OO format in order to ease my transition.

The problem? The lack of a simple tutorial to bridge between “ad hoc” functions and a more object oriented approach. Chris Klug was a big help in shedding some light on the subject for me, so I owe him a big “thank you”.

So here it is, a simple example.

Start Blend and create a new Silerlight 1 project called squareObject. Change the name of the default canvas to “rootCanvas” and set the dimensions to 800×600. Add another canvas called “content”. Don’t worry about the width/height of the content canvas - we’ll be taking care of that programmatically. Save the project.

First, we need to create a “constructor” for the square object class that we’re going to write. Create a new JS file in the project folder called objSquare.js, and type in the code for the constructor. The constructor function looks like this (don’t worry if this part doesn’t make sense yet - when you see the whole context, it will become clearer):

square = function(name, Parent, height, width, left, top)
{
this.initialize(name, Parent, height, width, left, top);
}

This is a constructor that will call the initialize function in the object class we’re about to code. We’re going to pass in a name for the object instance, the object parent, a height, width, left, and top position, so we are creating buckets to hold all of those values.

We want to continue on by creating the object class, which looks like this:

square.prototype =
{
initialize: function(name, Parent, height, width, left, top)
{
var xaml = ‘<Rectangle Name=”‘ + name + ‘” Canvas.Left=”‘ + left + ‘” Canvas.Top=”‘ + top + ‘” Width=”‘ + width + ‘” Height=”‘ + height + ‘” Fill=”#FFCC0000″/>’;

this._parent = Parent;
this._host = this._parent.getHost();
this._square = this._host.content.createFromXaml(xaml);
this._parent.children.add(this._square);
}
}

The class defines a function called initialize, which is called by the constructor that was created in the prior step. The initialize function creates a new rectangle object using the name, height, width, left, and top properties that were passed in, and then adds it to the “content” canvas, which is located using the “Parent” value that was passed.

Save the objSquare.js file.

This would be a good time to add a reference to this script file in the default.html page, so open that file up, and add the following script reference to the header section of the page:

<script type=”text/javascript” src=”objSquare.js” mce_src=”objSquare.js”></script>

While you’re in there, change the width and height styles to 800×600 as well so that they match the size of our root canvas.

Save the default.html file.

Now we want to make some edits to the Page.xaml.js file in order to make use of our square class when the application is loaded. Open the Page.xaml.js file. There’s some sample code in there that can be removed. The skeleton of the Page.xaml.js file should look like this:

if (!window.squareObject)
squareObject = {};

squareObject.Page = function()
{
}

squareObject.Page.prototype =
{
handleLoad: function(control, userContext, rootElement)
{
this.control = control;

}
}

The handleLoad function is called when Silverlight creates an instance of the “squareObject” app. Notice that control, userContext, and rootElement are all passed into the handleLoad function. Under the line that says “this.control = control;”, we’re going to add a few lines of code in order to set up references to the rootCanvas and content canvas objects. We also want to set the content cavas width and height to match the root canvas. To do that, this is the code that is used:

this.rootElement = rootElement;
this.content = rootElement.findName(”content”);

this.content.width = this.rootElement.width;
this.content.height = this.rootElement.height;

At this point, we’re ready to add code to call the constructor and have it create an object on the canvas for us, so let’s quickly review what we’ve done. We just finished modifying the Page.xaml.js file to create some references to the rootElement and content canvas, and made the content canvas resize to the size of the rootElement.

Before that, we created a square class in objSquare.js. In our square class, we added a constructor function which when called, will create an instance of the “square” object that is defined in the square.prototype class. We will now add some code to the Page.xaml.js file to create an object on the canvas.

Beneath the code you just added to the file, add the following code:

var newSquare = new square(”square1″, rootElement, 25, 25, 100, 100);

This code creates a new object called “newSquare” which is of the object type square. We passed the name “square1″ to be used in the XAML as a unique identifier for the XAML object, the rootElement, which is used to locate the parent object and insert the XAML into the content canvas, and then width, height, left, and right values.

Save the file and run.

You will see a small red square appear on the canvas. By manipulating these numbers, we can change the size or location of the object being created. We can also easily create multiple instances of an object. Add a line of code beneath the one you just added, with the following:

var newSquare1 = new square(”square2″, rootElement, 125, 125, 500, 500);

Run the project again, and you should see two squares.

If you’re looking to start moving towards object oriented programming, take some time and play with this example. I will be revisiting it in additional entries soon to add functionality and custom properties to the square class.

There’s also a good article on OO JavaScript here, though it’s not in the context of Silverlight, it’s still good stuff. The project files are here if you want to take the easy way out.

Original Author

Original article written by Jeff Paries

References
Published at DZone with permission of its author, Schalk Neethling. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)