Preprocessing JavaScript

Angelegt von niklas Thu, 07 Oct 2010 10:16:00 GMT

Just found this page and thought I'd give it a try. What I wanted to have was a less verbose way to define classes.

So here's a macro to conveniently define classes:

#define class(klass, ...) var klass = function(__VA_ARGS__)
Use it like this:
// class definition
class (Foo, bar) { // Foo: name of the class ; bar: first argument of initializer. can take arbitrary args.
  this.bar = bar;
};
// instantiation
var x = new Foo("xyz");
x.bar; //=> "xyz";
When processing that code with CPP (give it all the above code incl. macro as input) ...
/usr/bin/cpp -P -undef -Wundef -std=c99 -nostdinc -Wtrigraphs -fdollars-in-identifiers -C 
... this is what comes out (comments stripped):
var Foo = function(bar) {
  this.bar = bar;
}

var x = new Foo("xyz");
x.bar;

Now this is pretty convenient, but not the whole story. Here's how I'd like to define a method:

class(Foo) {
  def(bar, arg) {
    alert(arg);
  }
}

var x = new Foo();
x.bar("xyz"); // alerts "xyz"
Definitely possible:
#define def(method, ...) this. method = function(__VA_ARGS__)
Almost the same thing as the class. Here's the output:
var Foo = function() {
  this.bar = function(arg) {
    alert(arg);
  }
}

var x = new Foo();
x.bar("xyz");
Pretty rubyish, isn't it?

Well, this is not the end of the story of course, but it's a start. Anyway, I hope this will cause people to take a deeper look at the GNU cpp, which really doesn't deserve it's bad reputation as being dusty and old, and imho should get more attention outside the scope of C in general. Whatever. Use it or ignore it.

Trackbacks

Verwenden Sie den folgenden Link zur Rückverlinkung von Ihrer eigenen Seite:
http://praktikanten.brueckenschlaeger.org/trackbacks?article_id=317

Leave a comment

Comments