Home > Software design >  Add method to string prototype in JS-Interpreter
Add method to string prototype in JS-Interpreter

Time:01-09

I am wondering if there is a way to add new methods to prototype of string in Neil Fraser's JS-Interpreter. The documentation has no example for this and I am not really able to figure it out by the source code.

I expect (if there is a way) to be something similar to adding API calls to the interpreter's global object during creation.

What I have tried is the following:

const interpreter = require('js-interpreter');

var initFunc = function (interpreter, globalObject) {
  var stringPrototype = interpreter.nativeToPseudo(String.prototype);

  var stringGreetWrapper = function greet() {
    return "Hi "   this   "!";
  };

  interpreter.setProperty(stringPrototype, 'greet', interpreter.createNativeFunction(stringGreetWrapper));
};
        
var code = 'function foo(name) {return name.greet();}';
var myInterpreter = new interpreter(code, initFunc);
myInterpreter.appendCode('foo("John");');
myInterpreter.run();
var res = myIntepreter.value;

But it gives me an error: "undefined is not a function"

CodePudding user response:

Yes, you can do it very like that code adding alert, see inline comments (you can condense the code a bit, I wanted to show each step explicitly):

const initFunc = (interpreter, globalObject) => {
    // Get the interpreter's `String` constructor
    const stringFunction = interpreter.getProperty(globalObject, "String");
    // Get its `prototype` object
    const stringProto = interpreter.getProperty(stringFunction, "prototype");
    // Define our new function
    const newMethod = function () {
        // Note that we have to convert what we get to a primitive
        const str = String(this);
        // Show what we got
        console.log(`newMethod called on string ${JSON.stringify(str)}`);
    };
    // Add the method to the interpreter's `String.prototype`;
    // make it non-enumerable like most prototype methods are
    interpreter.setProperty(
        stringProto,
        "newMethod",
        interpreter.createNativeFunction(newMethod),
        Interpreter.NONENUMERABLE_DESCRIPTOR
    );
};

// Define and run some code using the new method
const myInterpreter = new Interpreter(`"somestring".newMethod();`, initFunc);
myInterpreter.run();
<script src="https://neil.fraser.name/software/JS-Interpreter/interpreter.js"></script>
<script src="https://neil.fraser.name/software/JS-Interpreter/acorn.js"></script>

  • Related