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

huangapple go评论62阅读模式
英文:

Add method to string prototype in JS-Interpreter

问题

Neil Fraser的JS-Interpreter中是否有一种方法可以向字符串的原型(prototype)添加新的方法呢?文档中没有相关示例,我也无法通过源代码来弄清楚。

如果有方法的话,我期望它类似于在创建解释器时向解释器的全局对象添加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 is not a function"。

英文:

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:

<!-- language: lang-js -->

const interpreter = require(&#39;js-interpreter&#39;);

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

  var stringGreetWrapper = function greet() {
    return &quot;Hi &quot; + this + &quot;!&quot;;
  };

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

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

答案1

得分: 0

是的,你可以这样做,很像那段代码添加了 alert,请看内联注释(你可以稍微压缩代码,我想明确展示每个步骤):

const initFunc = (interpreter, globalObject) => {
    // 获取解释器的 `String` 构造函数
    const stringFunction = interpreter.getProperty(globalObject, "String");
    // 获取它的 `prototype` 对象
    const stringProto = interpreter.getProperty(stringFunction, "prototype");
    // 定义我们的新函数
    const newMethod = function () {
        // 注意,我们必须将获取到的内容转换为原始值
        const str = String(this);
        // 显示我们得到的内容
        console.log(`newMethod called on string ${JSON.stringify(str)}`);
    };
    // 将该方法添加到解释器的 `String.prototype` 上;
    // 使其像大多数原型方法一样不可枚举
    interpreter.setProperty(
        stringProto,
        "newMethod",
        interpreter.createNativeFunction(newMethod),
        Interpreter.NONENUMERABLE_DESCRIPTOR
    );
};

// 定义并运行一些使用新方法的代码
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>
英文:

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):

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const initFunc = (interpreter, globalObject) =&gt; {
    // Get the interpreter&#39;s `String` constructor
    const stringFunction = interpreter.getProperty(globalObject, &quot;String&quot;);
    // Get its `prototype` object
    const stringProto = interpreter.getProperty(stringFunction, &quot;prototype&quot;);
    // 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&#39;s `String.prototype`;
    // make it non-enumerable like most prototype methods are
    interpreter.setProperty(
        stringProto,
        &quot;newMethod&quot;,
        interpreter.createNativeFunction(newMethod),
        Interpreter.NONENUMERABLE_DESCRIPTOR
    );
};

// Define and run some code using the new method
const myInterpreter = new Interpreter(`&quot;somestring&quot;.newMethod();`, initFunc);
myInterpreter.run();

<!-- language: lang-html -->

&lt;script src=&quot;https://neil.fraser.name/software/JS-Interpreter/interpreter.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;https://neil.fraser.name/software/JS-Interpreter/acorn.js&quot;&gt;&lt;/script&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年1月8日 21:28:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/75048127.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定