1

I have two similar functions, but one works and the other not

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], …}

Why is getEventListeners working inside the second function and not inside the first?

rajuGT
  • 6,224
  • 2
  • 26
  • 44
Dinkheller
  • 4,631
  • 5
  • 39
  • 67

1 Answers1

11

Firstly to all those question comments, getEventListeners is not custom method, it is the console api provided by browser.

getEventListeners(object)

getEventListeners(object) returns the event listeners registered on the specified object.

I executed the code which you have provided in the question. It just works fine in Firefox, check the attached snapshot

Firefox firebug

I executed the same in Chrome browser Chrome devtools

But this is not expected. As it is valid and also Firefox is doing right, the same should have been worked in chrome. I checked all the answers in var functionName = function() {} vs function functionName() {} and all other resources. It explains the scope/visibility of function declaration and function expression. But here the problem is visibility of getEventListeners function not function-working or function-notWorking.

So I think this must be defect in Chrome or the method getEventListerners should not be used in script, it is only for debugging purpose as specified in Command Line API Reference.

Note : This API is only available from within the console itself. You cannot access the Command Line API from scripts on the page.


More information

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] }
Community
  • 1
  • 1
rajuGT
  • 6,224
  • 2
  • 26
  • 44