直接分配事件处理程序实际的对象属性? [英] Are directly assigned event handlers actual object properties?

查看:153
本文介绍了直接分配事件处理程序实际的对象属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图回答这个问题:解释JavaScript中的奇怪行为。在研究过程中,我发现直接分配给主机对象的事件处理程序出现了一个奇怪的行为:它们可以作为对象的属性访问,但不知何故它们似乎不是实际属性。



例如,如果我在全局范围上定义一个变量,它看起来像窗口的任何其他属性:

  var foo =foo; 
console.log(Object.getOwnPropertyDescriptor(window,'foo'));
// Object {value:foo,可写:true,可枚举:true,可配置:false}

如果我分配给 window.foo ,或者如果我创建一个隐含的全局(但是[[Configurable]]将是 true ,出于已知原因;当然,这在严格模式下不起作用)。但是,如果我尝试通过分配给$ code> window.onsomething 来添加一个事件处理程序,那么我不能用 Object.getOwnPropertyDescriptor (虽然它仍然可以在 window.onsomething 下访问):

  window.onresize = function onresize(e){
console.log('rsz',e);
}
console.log(window.onresize); // function onresize(){...}
console.log(Object.getOwnPropertyDescriptor(window,'onresize')); // undefined

浏览器如何处理分配的事件处理程序?我怀疑这个答案也是另一个问题的答案。

解决方案

如果您查看 的MDN文档getOwnPropertyDescriptor ,它只报告直接在该对象上的属性,而不是在原型链中。例如,它适用于:

  Object.getOwnPropertyDescriptor(窗口,'位置')

但不适用于:

  Object.getOwnPropertyDescriptor(window,'onresize')

可能是因为 onresize 是在窗口继承的东西(因此在原型链中),而不是实际的窗口对象本身。


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.

解决方案

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.

这篇关于直接分配事件处理程序实际的对象属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆