从 chrome 开发者控制台调用 javascript 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23641434/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 01:16:47  来源:igfitidea点击:

Call javascript function from chrome developer console

javascript

提问by Starkers

Very simple script:

非常简单的脚本:

function foo(){
    return "bar"
}

console.log( foo() );

console:

安慰:

> bar // sanity test that proves everything's working
> foo(); // this guy is key!
> ReferenceError: foo is not defined

How should I call foo(); for debugging and experimentation purposes?

我应该如何调用 foo(); 用于调试和实验目的?

Is this not a practise? I love using IRB / Rails Console to verify my ruby code and want to do the same with JavaScript

这不是练习吗?我喜欢使用 IRB / Rails 控制台来验证我的 ruby​​ 代码,并希望用 JavaScript 做同样的事情

http://jsfiddle.net/m2muL/

http://jsfiddle.net/m2muL/

采纳答案by Travis J

The problem is that your foofunction is not part of the global scope. The console essentially has access to everything that windowdoes. As a result, if it is undefined there, then it is undefined in the console. For example, this could be an example of foo not being available in the console.

问题是您的foo函数不是全局范围的一部分。控制台基本上可以访问所做的一切window。结果,如果它在那里未定义,那么它在控制台中就是未定义的。例如,这可能是 foo 在控制台中不可用的示例。

(function(){
   function foo(){
     return "bar";
   } 
   console.log(foo()); //"bar"
})()

console.log(foo()); //ReferenceError: foo is not defined

Find a way to locate where this method is exposed. If it is inside of an object or method, make sure to reference that from your console.

找到一种方法来定位此方法的公开位置。如果它在对象或方法内部,请确保从您的控制台引用它。

var foobar = {
 foo: function(){ return "bar" ;}
};

console.log(foobar.foo()); //"bar"

If you cannot reference foo, then you cannot call it.

如果不能引用 foo,则不能调用它。

回答by Ralph N

You're trying to do this in JSFiddle, which is "hiding" your javascript away from your console. It's not really in scope for you to execute. It's not working there like you are assuming it will...

您正在尝试在 JSFiddle 中执行此操作,它会将您的 javascript 与控制台“隐藏”在一起。它实际上不在您执行的范围内。它并没有像你假设的那样在那里工作......

If you created a simple HTML file and stuck your javascript in there between tags, you wouldn't have a problem running "foo()" in console.

如果您创建了一个简单的 HTML 文件并将您的 javascript 卡在标签之间,那么在控制台中运行“foo()”就不会有问题。

Create test.html and put this inside:

创建 test.html 并将其放入:

<script>
function foo(){
    return "bar"
}
console.log( foo() );
</script>