I got stuck trying to answer this question: Explaining odd behavior in javascript. While researching, I found that event handlers assigned directly to host objects present a strange behavior: they can be accessed as properties of the object, but somehow they don't appear to be actual properties.
For example, if I define a variable on the global scope, it looks like any other property of window
:
var foo = "foo";
console.log(Object.getOwnPropertyDescriptor(window, 'foo'));
// Object {value: "foo", writable: true, enumerable: true, configurable: false}
I get the same output if I just assign to window.foo
, or if I create an implied global (but then [[Configurable]] would be true
, for known reasons; and, of course, that wouldn't work on strict mode). However, if I try to add an event handler by assigning to window.onsomething
, I can't read that property with Object.getOwnPropertyDescriptor
(although it's still accessible under window.onsomething
):
window.onresize = function onresize(e) {
console.log('rsz', e);
}
console.log(window.onresize); // function onresize(){...}
console.log(Object.getOwnPropertyDescriptor(window, 'onresize')); // undefined
How do browsers deal with event handlers assigned like that? I suspect the answer to this is also the answer to that other question.