【发布时间】: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