Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Metaprogramming

Is there a way to specify something similar to the following in javascript?

var c = {};
c.a = function() { }

c.__call__ = function (function_name, args) {
    c[function_name] = function () { }; //it doesn't have to capture c... we can also have the obj passed in
    return c[function_name](args);
}

c.a(); //calls c.a() directly
c.b(); //goes into c.__call__ because c.b() doesn't exist
like image 587
jameszhao00 Avatar asked Oct 04 '10 19:10

jameszhao00


People also ask

What is metaprogramming in JavaScript?

Metaprogramming is a programming technique in which computer programs have the ability to treat other programs as their data. This means that a program can be designed to read, generate, analyze, or transform other programs, and even modify itself while running.

What is metaprogramming example?

MetaProgramming gives Ruby the ability to open and modify classes, create methods on the fly and much more. A few examples of metaprogramming in Ruby are: Adding a new method to Ruby's native classes or to classes that have been declared beforehand. Using send to invoke a method by name programmatically.

What is the use of metaprogramming?

Metaprogramming can be used to move computations from run-time to compile-time, to generate code using compile time computations, and to enable self-modifying code. The ability of a programming language to be its own metalanguage is called reflection.

Are macros metaprogramming?

Meta-Programming uses a program as a data type to generate code; Macros and Reflection are techniques of Meta-Programming in some sense.


2 Answers

Mozilla implements noSuchMethod but otherwise...no.

like image 129
MooGoo Avatar answered Sep 24 '22 01:09

MooGoo


No, not really. There are some alternatives - though not as nice or convenient as your example.

For example:

function MethodManager(object) {
   var methods = {};

   this.defineMethod = function (methodName, func) {
       methods[methodName] = func;
   };

   this.call = function (methodName, args, thisp) {
       var method = methods[methodName] = methods[methodName] || function () {};
       return methods[methodName].apply(thisp || object, args);
   };
}

var obj = new MethodManager({});
obj.defineMethod('hello', function (name) { console.log("hello " + name); });
obj.call('hello', ['world']);
// "hello world"
obj.call('dne');
like image 41
Cristian Sanchez Avatar answered Sep 23 '22 01:09

Cristian Sanchez