问题
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.
回答1:
If you check the MDN documentation for getOwnPropertyDescriptor, it only reports properties that are directly on that object, not in the prototype chain.
For example, it works for:
Object.getOwnPropertyDescriptor(window, 'location')
but not for:
Object.getOwnPropertyDescriptor(window, 'onresize')
probably because onresize
is on something that window inherits from (therefore in the prototype chain), not on the actual window object itself.
回答2:
The window
object is an instance of the Window
constructor, which has onresize
as part of its prototype.
Try logging window
and enabling the show own properties only
option. onresize
will not be present, since it is inherited from Window
. This is why getOwnProperty
doesn't pick up on it, since it only returns descriptors for properties the object owns, rather than the ones originating in the prototype chain.
来源:https://stackoverflow.com/questions/13809917/are-directly-assigned-event-handlers-actual-object-properties