【问题标题】:cannot see a variable from Chrome Console but it's accessible in code无法从 Chrome 控制台看到变量,但可以在代码中访问
【发布时间】:2019-05-21 14:09:22
【问题描述】:

为什么可以从方法内部访问变量,但不能从浏览器控制台访问?

我有以下打字稿代码,使用 angular6,在 Windows 10 上通过 ng serve 运行,当前 Chrome。

import * as d3 from "d3"; // from "npm i d3 --save" version 5.7
// picking a member of d3, nothing magical about "scaleLinear" here
console.log("see", d3.scaleLinear) // it prints ok, ƒ linear() {...

// angular component code fragment below

somefunction() {
    console.log("see again", d3.scaleLinear) // it prints ok, again
    // add a break here
}

我将代码驱动到某个功能。休息时,我尝试在 Chrome 控制台中:

> console.log(d3.scaleLinear)

它会抛出一个错误:

VM2012:1 Uncaught ReferenceError: d3 is not defined
    at eval (eval at push../src/app/user-sel/user-sel.component.ts.UserSelComponent._resyncYSel (user-sel.component.ts:58), <anonymous>:1:13)
    at UserSelComponent.push../src/app/user-sel/user-sel.component.ts.UserSelComponent._resyncYSel (user-sel.component.ts:58)
    at UserSelComponent.push../src/app/user-sel/user-sel.component.ts.UserSelComponent.selYSel (user-sel.component.ts:166)
    at Object.eval [as handleEvent] (UserSelComponent.html:75)
    at handleEvent (core.js:21673)
    at callWithDebugContext (core.js:22767)
    at Object.debugHandleEvent [as handleEvent] (core.js:22470)
    at dispatchEvent (core.js:19122)
    at core.js:19569
    at HTMLSpanElement.<anonymous> (platform-browser.js:993)

如何直接在控制台中访问 d3?我错过了什么?我查看了有关此主题的旧 SO 问题52332640,但找不到确凿的答案。

【问题讨论】:

  • 你的页面有框架吗?
  • import * as d3 from "d3"; 不会在全局(窗口)范围内创建变量,它位于闭包内。例如,您可以写 window.d3 = d3; 来访问它
  • @ic3b3rg 我在访问d3.scaleLinear 后立即添加了debugger,但仍然无法访问控制台中的变量。
  • @wanjas 成功了,谢谢。导入后我分配了window.d3=d3;,现在可以在控制台中访问它。那么如果没有额外的赋值,这个变量在哪里呢?

标签: javascript typescript google-chrome-devtools


【解决方案1】:

如果您的页面有任何框架,则您的控制台可能在错误的上下文中运行。 有一个下拉菜单可让您指定正确的上下文

例如,在此屏幕截图中,有两个 IFrame 元素。为了从“contentIframe2”中运行的脚本访问变量,我必须切换上下文

【讨论】:

  • 不,我没有使用任何框架,但很高兴提醒您这一点
猜你喜欢
  • 2019-10-29
  • 1970-01-01
  • 2013-03-17
  • 2011-06-06
  • 2020-05-03
  • 2015-09-19
  • 2021-09-10
  • 2014-12-06
  • 1970-01-01
相关资源
最近更新 更多