Initialize, you have to do it

I had been working purely in javascript and PHP for almost two years already. And even then I haven’t had any experience in object oriented PHP. Before working at ea, all object oriented programming I was doing was making object prototypes in javascript. I actually made some pretty nifty small objects that way. My problem with working with prototypes however is that you’re not actually working with classes. Javascript just doesn’t have syntax for creating classes. You can’t simply have:

    class MyClass
        public int number;
        public MyClass()
            number = 0;

Instead, in Javascript, you would have the following:

    var MyClass = function(){};

    MyClass.prototype = {
            mynumber = 0;

And for the most part, this works fine. I’ve gotten used to working with prototypes to create new objects. And if you use one of the great many javascript libraries, or even if you don’t, there are other probably easier ways to create objects.

The reason I have a problem though, and I mention it because it took me a while to remember otherwise, is that you can’t instantiate a member variable in the prototype declaration. In the above example, trying to initialize mynumber in that same line gives you a public static variable. So, if you have a good number of variables that can be initialized with a value, in javascript you would have to initiate all of them in in the constructor or an initialize function. So, that means at least one line per variable. Yes, sure, it’s minor pet peeve in adding extra lines, but man is it annoying having to remember that. If i can initialize it where I create it, I don’t have to worry about remembering to initialize it again.

It actually took me a while to remember that I could initialize my variables. And man am I enjoying it.

July 17, 2007 10:53 PM Scripting


Leave a comment of your own

If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.

Use of HTML for comments is not available.

In an effort to combat spam, you will be able to post your comment after you preview.

Powered by Movable Type 3.2 Creative Commons License: Some Rights Reserved © 2000-2005

Site feeds. Hofully valid XHTML and CSS. No kitties were harmed in the making of this website.