JSFiddle - React, Tailwind, and code Playground

by Tonio Loewald

HTML

<h2>
Deferred Method Parsing
</h2>
<p>
  Methods are replaced with a call to makeFunctionFactory which is passed the code that will be parsed to create the method. If module variables are accessed by the method, they will need to have getters and setters created and baked into the source.
</p>

JavaScript

function makeFunctionFactory(constructor, name, code) {
  return function() {
    print('parsing function', 'p', 'red');
      var fn = new Function(code); this[name] = Foo.prototype[name] = fn;
      return fn.apply(this, arguments);
    }
  }

  function Foo(x) {
    this.x = x;
  }

  var private = 0;

  Foo.prototype = {
    normal: function(a, b) {
      var s = a + b;
      this.x += s;
      private++;
      return a + ' + ' + b + ' = ' + s + ', total so far: ' + this.x + ', calls so far: ' + private;
    },

    _private: function(x) {
    	if(x!==undefined){private=x;}
      return private;
    },
    dehydrated: makeFunctionFactory(Foo, 'dehydrated', "var _=arguments,a=_[0],b=_[1],private=this._private();var s = a + b; this.x += s; this._private(private+1); return a + ' + ' + b + ' = ' + s + ', total so far: ' + this.x + ', calls so far: ' + this._private();"),
  }

  /*----------------------------------------*/
  function print(msg, tag, color) {
    var d = document.createElement(tag || 'p');
    d.textContent = msg;
    d.style.color = color;
    document.body.appendChild(d);
  }

  print('Normal Methods', 'h3');
  var bar = new Foo(0);
  var foo = new Foo(0);
  var baz = new Foo(0);
  print('Normal Methods', 'h3');
  print(foo.normal(1, 1));
  print(foo.normal(2, 3));
  print('Deferred Methods', 'h4');
  print(foo.dehydrated(1, 1));
  print(foo.dehydrated(2, 3));
  print('instance created before foo', 'h4');
  print(bar.dehydrated(1, 1));
  print(bar.dehydrated(2, 3));
  print('instance created after foo', 'h4');
  print(baz.dehydrated(1, 1));
  print(baz.dehydrated(2, 3));
  var blah = new Foo(0);
  print('instance created after dehydrated parsed', 'h4');
  print(blah.dehydrated(1, 1));
  print(blah.dehydrated(2, 3));