NodeJS 在JS-Interpreter中为字符串原型添加方法

7d7tgy0s  于 2023-01-12  发布在  Node.js
关注(0)|答案(1)|浏览(122)

我想知道是否有一种方法可以在Neil Fraser's JS-Interpreter的字符串原型中添加新的方法。documentation没有这样的例子,我也不能通过源代码来理解它。
我希望(如果有办法的话)类似于在创建过程中向解释器的全局对象添加API调用。
我所尝试的如下:

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;

但它给了我一个错误:“undefined不是函数”

eivnm1vs

eivnm1vs1#

是的,您可以像添加alert的代码那样做,请参见内联注解(您可以压缩代码,我希望明确显示每一步):

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>

相关问题