JS函数作为变量[getEventListeners API]工作

Din*_*ler 0 javascript function

我有两个类似的功能,但一个工作,另一个不工作

function notWorking(el) {
    return getEventListeners(el);
}
notWorking(document);
// result --> Uncaught ReferenceError: getEventListeners is not defined

working = function(el) {
    return getEventListeners(el);
}
working(document);
// result --> Object {keyup: Array[1], …}
Run Code Online (Sandbox Code Playgroud)

为什么getEventListeners在第二个函数内部工作而不在第一个函数内?

raj*_*uGT 9

首先是所有那些问题评论,getEventListeners不是自定义方法,它是浏览器提供的控制台api.

getEventListeners(对象)

getEventListeners(object)返回在指定对象上注册的事件侦听器.

我执行了你在问题中提供的代码.它在Firefox中工作正常,检查附加的快照

Firefox firebug

我在Chrome浏览器中 执行了相同的操作Chrome devtools

但这不是预期的.因为它是有效的,而且Firefox也是正确的,同样应该在chrome中使用.我检查了var functionName = function(){} vs function functionName(){}以及所有其他资源中的所有答案.它解释了函数声明和函数表达式的范围/可见性.但这里 的问题是getEventListeners函数的可见性不是函数工作或函数工作.

所以我认为这必须是Chrome中的缺陷,或者该方法getEventListerners不应该在脚本中使用,它仅用于命令行API参考中指定的调试目的.

注意:此API仅在控制台本身内可用.您无法从页面上的脚本访问命令行API.


更多信息

getEventListeners.toString()
> "function getEventListeners(node) { [Command Line API] }"

this.getEventListeners
> undefined          //function is not accessible via window object

// where as

this.setTimeout
> setTimeout() { [native code] }
Run Code Online (Sandbox Code Playgroud)