Making Abstract classes in JavaScript
Posted: Fri Oct 13, 2006 7:45 am
Since JavaScript doesn't support interfaces (does NS support them actually? I noticed it's a reserved word in NS!) does anybody have a better approach than this?
Code: Select all
function MyAbstractClass()
{
this.someCommonMethod = function() {} //These would implement some actual functionality
this.someOtherMethod = function() {}
this.someAsbtractMethod = function()
{
throw new Error('MyAbstractClass.someAbstractMethod must be overridden by child');
}
}
function MyClassUsingTheInterfaceOfTheAbstractClass()
{
this.performOperationOnObject = function(obj)
{
//Cheap and dirty type checking
if (!(obj instanceof MyAbstractClass))
{
throw new Error('MyClassUsingTheInterfaceOfTheAbstractClass.performOperationOnObject requires parameter 1 to be object of type MyAbstractClass');
}
obj.someCommonMethod();
obj.someOtherMethod();
obj.someAbstractMethod();
}
}
function MyOverridingClass()
{
this.someAbstractMethod = function() {}
}
MyOverridingClass.prototype = new MyAbstractClass;
var myObject = new MyClassUsingTheInterfaceOfTheAbstractClass();
myObject.performOperationOnObject(new MyOverridingClass());