无法读取未定义的属性“对象”

时间:2019-11-28 09:22:39

标签: javascript scala.js

我正在尝试在网页中包含一个生成的js模块。却给我一个错误:Uncaught TypeError: Cannot read property 'Object' of undefined处的$g["Object"]["freeze"]($env);

最小的示例是:

文件index.html

<html>
  <head>
    <meta content="text/html;charset=utf-8" http-equiv="Content-Type"/>
  </head>
  <body>
    <!-- Note the usage of `type=module` here as this is an ES6 module -->
    <script type="module">

      import { foo } from './foo.js';

      console.log(foo());

    </script>
  </body>
</html>

文件foo.js

'use strict';
/* Scala.js runtime support
 * Copyright 2013 LAMP/EPFL
 * Author: Sébastien Doeraene
 */

/* ---------------------------------- *
 * The top-level Scala.js environment *
 * ---------------------------------- */

// Get the environment info
var $env = (typeof __ScalaJSEnv === "object" && __ScalaJSEnv) ? __ScalaJSEnv : {};

// Global scope
var $g =
  (typeof $env["global"] === "object" && $env["global"])
    ? $env["global"]
    : ((typeof global === "object" && global && global["Object"] === Object) ? global : this);
$env["global"] = $g;


$env["exportsNamespace"] = void 0;


// Freeze the environment info
$g["Object"]["freeze"]($env);

export function foo() { return "Hello"; }

但是如果我只是将脚本复制粘贴到chrome控制台中,那么一切都会正常进行。

1 个答案:

答案 0 :(得分:1)

您在Scala.js 0.6.x中遇到了一个错误:https://github.com/scala-js/scala-js/issues/3677var $g = ...中的全局检测代码在Node.js以外的ES模块中(例如,在浏览器中)使用时不正确,并且无法发现正确的全局对象。

该问题提到了一种解决方法:在HTML文件中添加以下<script>标签(在导入Scala.js代码的标签之前):

<script type="text/javascript">
var __ScalaJSEnv = { global: window };
</script>

这将明确告诉Scala.js全局对象是什么,即window

此问题已在Scala.js 1.x(其RC1 was released two days ago)中得到解决。

相关问题