zomgistania

Main page | About | Articles | Previous Posts | Archives

Monday, August 14, 2006

More Object-Oriented JavaScript

Here's some more stuff related to OO-JavaScript

How to create a function which is both callable from inside the class and from outside?

This had caused me some problems up to now... I wasn't able to make a function inside a class work from both inside the class and from outside. Here's how to "properly" create one of those:


function Example()
{
this.FunctionName = InternalFunctionName

function InternalFunctionName()
{
// do something funky
}
}


In the above example, the InternalFunctionName function is callable with that name from inside the class. From outside, the same function is callable with the name FunctionName. Of course they can both share the same name, the different name was just for the sake of the example.



Expanding objects

In JavaScript, you can easily expand objects/classes which already exist. For example, you can add a function to the built-in Array object.


Array.prototype.SayHello = function()
{
alert('hello');
}


After doing that, all Array objects can show you an alert box containing text Hello. Yeah, it's pretty useless but it works as an example. You could take the CopyArray and Equals functions from my post about comparing and copying arrays in JS and add those if you wanted something useful.

You can also add functions to already existing instances, which isn't very useful but possible


var s = new SomeClass();
s.DoSomething = function()
{
//do something
}



Inheriting from a base-class

To inherit from a base-class, do the following


function BaseClass()
{
function A()
{
//something
}
}

function OtherClass()
{
//inherit from BaseClass
this.prototype = BaseClass.prototype;
}


This would make OtherClass get function A from BaseClass. Very simple, but the syntax is probably a bit different from what it usually is.

Labels: ,

0 Comments:

Post a Comment

<< Home