简体   繁体   English

如何从浏览器控制台调用 function?

[英]How to call the function from browser console?

I need to call the function from browser console for testing purpose?我需要从浏览器控制台调用 function 进行测试吗?

test is working as expected, but test2 is not working测试按预期工作,但 test2 不工作

function test() {
  alert(0);
}
(function(e, t) {
  var test2 = (function() {
    alert(2)
  })
})

Calling for browser console调用浏览器控制台

test() // its working

test2() // Uncaught ReferenceError: test2 is not defined

There are two basic problems here:这里有两个基本问题:

test2 never exists test2从不存在

test2 is defined inside a function which is never called, so it is never defined. test2在 function 中定义,该 function 从未被调用,因此从未定义。

The code would have to actually call the anonymous function it is inside.代码必须实际调用它在里面的匿名 function。

However, assuming that is a side effect of you truncating the code for this question and in your real case that anonymous function does get called:但是,假设这是您截断此问题的代码的副作用,并且在您的实际情况下,匿名 function 确实被调用:

test2 isn't a global test2不是全局的

So in order to access it, you need to be in the right scope.所以为了访问它,你需要在正确的 scope 中。

The only way to do that for the console would be to:对控制台执行此操作的唯一方法是:

  1. open up the sources tab of the browser's developer tools打开浏览器开发者工具的标签
  2. add a breakpoint inside the anonymous function在匿名 function 中添加断点
  3. run the code until your reach the breakpoint运行代码直到到达断点
  4. then use the console to access test2 which is now in scope.然后使用控制台访问test2 ,它现在位于 scope 中。

Note that given the structure of that code you might have to put the breakpoint before test2 has a value assigned to it and then step through the code until after it is defined.请注意,鉴于该代码的结构,您可能必须在test2为其分配值之前放置断点,然后单步执行代码直到定义它之后。

Since your test2 var is a function on it's own, no need to wrap them in () .由于您的test2 var 本身就是 function ,因此无需将它们包装在()中。

Copy/paste this into browser console to check;将其复制/粘贴到浏览器控制台中进行检查;

var test2 = (function() {
    alert(2)
});
test2();

Advanced JavaScript: Why is this function wrapped in parentheses? 高级 JavaScript:为什么这个 function 用括号括起来?


Should you really want those parentheses, you can call the existing function like so;如果你真的想要这些括号,你可以像这样调用现有的 function;

 (function(e, t) { var test2 = (function() { alert(2) }); test2(); // <-- Run function })() //^^ Extra parentheses to instantly run wrapper function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM