【问题标题】:Function toString() not working函数 toString() 不起作用
【发布时间】:2015-05-15 14:34:11
【问题描述】:

我在我的 QML 应用程序中使用 Javascript,并希望将函数的 代码 作为字符串插入:

function test(parameter) {
    console.log("Something to do!");
}
...
function otherFunction(otherParam) {
    console.log("Output: "+test.toString());
}

所有这些都是打印以下内容:

"Output: function() { [code] }"

而不是所需的字符串:"Output: function() { console.log("Something to do!"); }"

P.S.:我记得这段代码最近可以工作,但是在从 Qt 5.2 迁移到 Qt 5.4 并修复 CMake 脚本的某个地方,它坏了。

这里有什么问题?

【问题讨论】:

  • 您应该提交一个 Qt 错误,参考第 5 版。 ECMA-262,秒。 15.3.4.2 - 标准行为是使用 FunctionDeclaration 语法返回对象的文本表示。据推测,标准的含义是这种表示应该是可用的,而不仅仅是空函数的表示(正确的语法,不正确的含义)。
  • 嗯,我们希望有一个可用的解决方法。同时我已经报告了这个错误:bugreports.qt.io/browse/QTBUG-46122

标签: javascript qt qml qt5


【解决方案1】:

toString 应用于函数是一个实现细节。根据 ECMA-262,它应该可以按您的预期工作,但显然,在实施时,它不会:( 无论如何,该标准允许它在不同的实现之间以不同的方式工作。

您依赖于一个实现细节,然后更改了您的实现,所以您不应该感到惊讶。

如果确实需要存储代码,可以通过eval-uating一个字符串来生成函数,然后将代码添加为函数的属性。

根据5th edition of ECMA-262,第 15.3.4.2 节,Function.prototype.toString() 应返回具有 FunctionDeclaration 语法的实现定义的再现。所以也许 Qt 的 JS 引擎在这里表现出非标准行为。

【讨论】:

    【解决方案2】:

    这似乎工作得很好。

    function test(parameter) {
        console.log("Something to do!");
    }
    
    function otherFunction(otherParam) {
        console.log("Output: "+test.toString());
      	document.getElementById('log').innerHTML = "Output: "+test.toString();
    }
    
    otherFunction("foo");
    <p id="log"></p>

    同时检查控制台日志。

    【讨论】:

      猜你喜欢
      • 2015-12-01
      • 1970-01-01
      • 2015-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多