JavaScript and Macro Usage - 2

Let's get to know the JavaScript macro library named sweet.js!

Tue, 07 Oct 2014

Sweets

Intro

In the previous post, we studied some very simple examples of JavaScirpt macro structures. Macros can have many uses; Some of them write rapid prototyping or algorithm, but macros definitely have the potential to offer you more. It’s up to your imagination.

Let’s expand our examples a little more with a class notation example written in a macro:

Example: Class Syntax

Let’s say you want to create a JavaScript class object. To do this with JavaScript, you can use the prototype feature to write the following code:

function Person(name) {
    this.name = name;
}
Person.prototype.say = function(msg) {
    console.log(this.name + " says: " + msg);
}

The Person object described above and the “say” method can then be used as follows:

var you = new Person("Omer");
you.say("I love JavaScript!");

//Console Output
>Omer says: I love JavaScript!

So what if we want to write the same object with the “class” syntax? We have three options:

  1. Leave JavaScript and continue to write with Java. ( emoji-smile )
  2. Wait for ES6 Standards to become widespread.
  3. Using sweet.js !

If you want to create an object using the Java-like “class” syntax with sweet.js, just define a few lines of macro:

macro class {
 
  rule {
 
    $className {
        constructor $cparams $cbody
        $($mname $mparams $mbody) ...
    }
 
  } => {
 
    function $className $cparams $cbody
 
    $($className.prototype.$mname
      = function $mname $mparams $mbody; ) ...
 
  }
}

That’s it. You can now define a “class” with JavaScript:

class Person {
  constructor(name) {
    this.name = name;
  }
  say(msg) {
    console.log(this.name + " says: " + msg);
  }
}
var you = new Person("Omer");
you.say("Macros are sweet!");

Console:

>Omer says: Macros are sweet!

Summary

I think sweet.js is an extremely powerful tool and, frankly, when I first saw it, I had the feeling that macros could give direction to the future for JavaScript.

Macro Hygiene, which comes up with the concept of Macro, and the use of a macro to replace Google Closure Compiler and similar compilers can be mentioned in another article.

In the meantime, if you are interested in examples, you can review more Macros:

(I highly recommend the macro Randomly Disappearing Code Random macro example, which is made entirely for fun. emoji-smiley )

Further Reading

Fun Stuff
Loading...
Omer Gurarslan

Omer Gurarslan is a software developer based in London who loves developing Web & Mobile Applications using modern frameworks and JavaScript.