Think JavaScript is only good for image swaps and flying <div>s?Think again - this article takes an in-depth look at some of theobject-oriented constructs available in JavaScript, and demonstrates howJavaScript objects can substantially speed up code development anddeployment.
You've probably already used JavaScript objects before - for example, the code
<script language="JavaScript">
a = new Image();
</script>
creates a new instance of the Image object, while
<script language="JavaScript">
x = new Date();
</script>
creates a new instance of the Date
object.
JavaScript comes with numerous built-in objects, each with pre-defined methods and properties...but what if you want to roll your own?
Well, it isn't very difficult - as a matter of fact, it's almost identical to writing a JavaScript function.
<script language="JavaScript">
// object constructor
function Sumthing() {
}
</script>
You can create an instance of the Sumthing object like
this:
<script language="JavaScript">
// object instance
obj = new Sumthing();
</script>
Note the all-important "new" keyword - this is how
JavaScript knows that you're trying to create an instance of an object, rather than merely running a function.
The code above creates an instance named "obj" of the object Sumthing. You can verify that it is indeed an object, oh yes, by popping up an alert().
<script language="JavaScript">
obj = new Sumthing();
alert(obj);
</script>