为什么 hasOwnProperty 在 Event 对象的属性上报告错误?

问题描述

我有一个始终只有两个参数的函数

  • e 是第一个参数
  • myString 是第二个参数,认为 null

使用单个 string 参数调用函数

我不知道该函数是直接触发还是通过事件侦听器触发。

  1. 如果函数由事件侦听器触发,则 e 变为 Event 对象,myString函数调用中提供的字符串填充。这是一个理想的结果。

  2. 如果直接触发相同的函数,则 e函数调用中提供的字符串填充,而 myString 保持为 null

然后我可以在函数的第一行中使用三元修复 2(在没有任何更好的方法的情况下):

myString = (e.hasOwnProperty('type')) ? myString : e;

此时 e 可能仍然是一个字符串,但没关系 - 该函数已被直接调用,所以从现在开始我将忽略它。

在我看来这些都不是处理事情的好方法,但我的限制是有时第一个函数参数将是一个 Event 对象,所以我需要考虑它,即使函数被直接调用

暂时撇开 e.hasOwnProperty('type') 是验证 Event 对象的糟糕方法这一事实(实际上任何对象都可以有一个密钥 type,不是吗?),我现在发现 e.hasOwnProperty('type') 总是报告错误

这是一个例子:

const myButton = document.querySelector('button');

const clickButton = (e,f = {a: 'b'},g = {type: 'c'}) => {

  console.log(e.hasOwnProperty('type'));
  console.log(e.type !== undefined);
  
  console.log(f.hasOwnProperty('type'));
  console.log(f.type !== undefined);
  
  console.log(g.hasOwnProperty('type'));
  console.log(g.type !== undefined);
}

myButton.addEventListener('click',clickButton,false);
<button type="button">Click Me</button>

为什么 e.hasOwnProperty('type') 总是报错?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)