Object-Oriented Client-Script

We hear so much about Object-Oriented JavaScript, but its all hacks. I have a solution that gives you Classes in JavaScript. Yes, finally, Classes in JavaScript!

Just make you’re REAL CLASSES using VBScript, a true OBJECT-ORIENTED coding language.

    <script type="text/VBScript">
      Function NewPerson()
          Set NewPerson = New Person
      End Function
      Class Person
          Private p_Name
          Private Sub Class_Initialize()
              Name = "Cool Person"
          End Sub
          Property Get Name
              Name = p_Name
          End Property
          Property Let Name(ByVal in_Name)
              p_Name = in_Name
          End Property
      End Class
    </script>

Now you can create an instance of your REAL CLASS from JavaScript.

    <script type="text/javascript">
      try {
        var person = NewPerson();
        alert("You are now using Classes in JavaScript. You created a Person with name of: " + person.name);
      }
      catch (err) {
        //You could also redirect to a Funcional Programming version of your site here.
        alert("Lol, your browser doesn't support Classes (yet). Hang in there buddy! Or use IE.");
      }
    </script>

You can see a real world scenario sample online! http://jsbin.com/OrobAMO/1/edit

Right now, this only works in Internet Explorers 6, 7, and 8 and probably 9 and maybe even 10. But EgmaScript 6 (also known as ES6) will be out soon, which is the next upgrade of Javascript and will support Classes. So when that is done you can just copy this code to use that, which will probably be nearly identical format. At that point, this code will work in pretty much all browsers. Until then, you can use this pollyfill.

About Banzor

Chris Bannon is a Corny Dad. He is a Certified Internet Webmaster and a purveyor of Fine Scripts. Chris is a Both-end Developer from JS to C#. And a Grinder for the Pittsburgh Pharaohs hockey team. View all posts by Banzor →

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>