简体   繁体   English

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

[英]How to call anonymous functions in chrome developer tool?

Here is my code:这是我的代码:

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

How can I call the sayHi() function from chrome developer tools?如何从 chrome 开发者工具中调用 sayHi() function?

sayHi is scoped to the IIFE it is declared inside. sayHi的范围是它在里面声明的 IIFE。

You can therefore only call it:因此,您只能将其称为:

  • From the same scope来自同一个scope
  • From a scope you copy the function to从 scope 复制 function 到

From the same scope来自同一个scope

You need to move the scope of the Chrome Console into the function.您需要将 Chrome 控制台的 scope 移动到 function 中。 You can do this by adding a breakpoint inside the IIFE (via the Sources panel) and then causing the IIFE to rerun by reloading the page.您可以通过在 IIFE 中添加一个断点(通过 Sources 面板)然后通过重新加载页面使 IIFE 重新运行来做到这一点。

Then you can call the function as normal.然后您可以正常调用 function。

动画演示如何添加断点

Copy the function to a different scope将 function 复制到不同的 scope

This requires that you edit the source code.这需要您编辑源代码。 The general way to do this is by returning a value from the 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");

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

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