Quantumwave Interactive Inc.
  Interactive media development . Programming . Design . Consulting

Invoking a dynamic class method

Someone brought up the question "How to invoke a dynamic class method pulled from a database?"

Well, here's one way to do it. The variables 'theClass', 'cMethod' and 'iMethod' could be retrieved from any data source. Needless to say, the class and methods have to exist, or can be loaded dynamically as well.


var theClass = "MyClass";
var cMethod = "classMethod";
var iMethod = "instanceMethod";

MyClass = function() {
   // class constructor
};

MyClass.classMethod = function() {
   // this is a class (static) method
   var a = arguments;
   var len = a.length;
   trace("MyClass.classMethod arguments: "+ len);
   for (var i=0; i<len; i++) {
      trace("\t"+ i +": "+ a[i] + " ("+ typeof a[i] +")");
   }
};

MyClass.prototype.instanceMethod = function() {
   // this is an instance method
   var a = arguments;
   var len = a.length;
   trace("MyClass.prototype.instanceMethod arguments: "+ len);
   for (var i=0; i<len; i++) {
      trace("\t"+ i +": "+ a[i] + " ("+ typeof a[i] +")");
   }
   return Math.PI * a[0] * a[0];
};

// invoke a dynamic class method
invokeClassMethod = function(className, methodName) {
   arguments.splice(0,2);
   return eval(className)[methodName].apply(null, arguments);
};

// invoke a dynamic instance method
invokeInstanceMethod = function(className, methodName) {
   var c = eval(className);
   arguments.splice(0,2);
   return new c()[methodName].apply(null, arguments);
};

// tests

invokeClassMethod(theClass, cMethod, 42, "MoL", false);
trace(invokeInstanceMethod(theClass, iMethod, 10));

Trace output:

MyClass.classMethod arguments: 3
   0: 42 (number)
   1: MoL (string)
   2: false (boolean)
MyClass.prototype.instanceMethod arguments: 1
   0: 10 (number)
314.159265358979
Download source file: dynamic_class_method.zip (Flash MX)

Last updated on: May 10, 2002 - Copyright © 2002 Dave Yang / Quantumwave Interactive Inc.

home | about | news | flash | director | shockwave | download | dave | résumé | contact

Copyright © 1995-2009 Quantumwave Interactive Inc.