chrome开发者工具如何调用匿名函数?

How to call anonymous functions in chrome developer tool?

这是我的代码:

(function(params) {
  function sayHi(text) {
    console.log(text);
  }
  sayHi("Hello world")
})()

如何从 chrome 开发者工具中调用 sayHi() 函数?

sayHi 作用域为它在内部声明的 IIFE。

因此您只能调用它:

  • 来自同一范围
  • 从作用域将函数复制到

来自同一范围

您需要将 Chrome 控制台的范围移动到函数中。您可以通过在 IIFE 中添加一个断点(通过“源”面板)然后通过重新加载页面使 IIFE 重新运行来完成此操作。

然后就可以正常调用函数了

将函数复制到不同的范围

这需要您编辑源代码。这样做的一般方法是从 IIFE 返回一个值。

const sayHi = (function(params) {
  function sayHi(text) {
    console.log(text);
  }
  sayHi("Hello world");
  return sayHi;
})()

sayHi("This can now be called from outside the function, if this is the global scope it will be accessible to the Chrome Console");