javascript - D3.js : Uncaught TypeError: Cannot read property 'document' of undefined

标签 javascript d3.js initialization undefined

我在 d3.js 初始化方面遇到了一个非常奇怪的问题。在 d3.js 脚本中,一开始它尝试获取 var d3_document = this.document; 但它弹出以下错误:

Uncaught TypeError: Cannot read property 'document' of undefined

调试时,this.document 返回未定义。

我正在使用 yo webapp 生成项目。它使用 bower 作为包管理器,并使用 gulp 进行构建过程(使用 babel 实现 ES2015 功能)。

有趣的是,我已经用 xampp 对其进行了测试,它运行良好!

我会很感激一些建议!谢谢!

最佳答案

这听起来像是在 D3 脚本文件的开头插入 "use strict"; 或将其组合到另一个文件中并在顶部加上 "use strict"的东西(很可能是 Babel)。这意味着 this 在全局范围内(或在没有特定 this 的函数中调用)不再是对全局对象的引用,它是 undefined . (而在“松散”模式下或在没有特定 this 值的函数中,全局范围内的 this 是对全局对象的引用,也可以通过全局变量`window1.)

您需要从 Babel 转换的脚本列表中删除您的 d3.js 并按原样包含它。假设您使用的是普通的 d3.js 文件,它看起来像这样:

!function() {
  var d3 = {
    version: "3.5.16"
  };
  var d3_arraySlice = [].slice, d3_array = function(list) {
    return d3_arraySlice.call(list);
  };
  var d3_document = this.document;
  // ...
  // ...
  // ...lots of stuff here...
  // ...
  // ...
}();

这依赖于在松散模式下运行。

关于javascript - D3.js : Uncaught TypeError: Cannot read property 'document' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35560305/

相关文章:

javascript - 使用 Identity Server 4 和 ASP.NET Identity 添加外部登录

javascript - 鼠标弹起与点击

javascript - 检查元素是否有滚动-reactjs

javascript - D3JS中的自定义轴函数

cocoa-touch - 使用 loadNibNamed 时未初始化子类 UITableViewCell

c++ - 通过 const_cast 进行的这个 const 初始化是否有未定义的行为?

javascript Regex 日期早于 1970 年 1 月 1 日

d3.js - d3 : how do the create and update selections work? 中的可重用图表

svg - 如何在D3轴刻度中获取数字值而不是对数值?

c++ - 使用大括号初始化类实例