Function Munger

by khrome

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/mootools/1.4.5/mootools-core-full-compat.js"></script>

JavaScript

//var original_apply = Function.prototype.apply;
Function.prototype.$ = function(context, arg){
    if(context === 'context'){
    	  if(!arg){
          this.dskjdshjh = function(){
              return this.callee;
          };
          var cx = this.dskjdshjh();
          delete this.dskjdshjh;
          return cx;
        }else{
        	this.dskjdshjh = new Function('return '+arg);
          var cx = this.dskjdshjh();
          delete this.dskjdshjh;
          return cx;
        }
    }
    if(typeof context === 'function'){
       var func = this;
       var $ = this.$;
       return function(){
       		var args = Array.prototytpe.slice.call(arguments);
          var ctx = $('context');
       		return context(ctx, func.apply(ctx, args));
       }
    }
    if(typeof context === 'string'){
    		var body = this.toString();
        var args = body.substring(
            body.indexOf('(')+1, 
            body.indexOf(')')
        ).split(',').map(function(item){ return item.trim() });
        var lines = body.substring(
            body.indexOf('{')+1, 
            body.lastIndexOf('}')
        ).split(';').map(function(item){ return item.trim() }).filter(function(i){ return !!i });
        var target = arg < 1?lines.length-arg:(arg || 0);
        var spliceArgs = context.split(';')
            .map(function(item){ return item.trim() })
            .filter(function(i){ return !!i });
        spliceArgs.unshift(0);
        spliceArgs.unshift(target);
        lines.splice.apply(lines, spliceArgs);
        eval.call(window, 'var newFunction = function('+args+'){'+lines.join(";\n  ")+'}');
        var ctx = this.$('context');
        return function(){
        	return newFunction.apply(ctx, arguments);
        };
    }
}

var pwargh = 'a';
var func = function(will, obey, commands){
//console.log(pwargh);
	return 'This function uses'+this.value; 
};
pwargh = 'bbbb';

newFunc = func.$("console.log(this.value);\nconsole.log(pwargh);");

document.writeln('==>:...