如何判断是不是event对象

可不可以用event instanceof Event的方式来判断一个对象是不是event对象,兼容性如何?会有什么问题么?

阅读 5k
4 个回答

可以判断event对象里面是否有某个属性。比如input,那event里面是不是有target这个属性。
image.png

使用Object.prototype.toString

window.onresize = (e) => {
  console.log(Object.prototype.toString.call(e));
// [object Event]
}

console.log(Object.prototype.toString.call(1))          // '[object Number]'
console.log(Object.prototype.toString.call(1n))         // '[object BigInt]'
console.log(Object.prototype.toString.call('123'))      // '[object String]'
console.log(Object.prototype.toString.call(null))       // '[object Null]'
console.log({}.toString())         // '[object Object]'
console.log(Object.prototype.toString.call([]))         // '[object Array]'
console.log(Object.prototype.toString.call(function a() {}))  // '[object Function]'

参考我的文章: https://segmentfault.com/a/11...

探测可能“未知”的对象以获得您希望找到的属性和方法是一个很好的实践。所以,假设你有一个事件对象,并在对它进行操作之前探测它。

if (event.target)
{
   //looks like we're an event, hide the target
   var e=$(event.target);
   e.hide();
}

需要注意的是,我并不是建议你通过检测‘target’属性,来看看它是否是一个事件:你在测试target属性,因为你要使用这个属性。我想说的是,与其试图弄清楚一个对象是否为event,不如探测这个对象,看看它是否会按照您期望的方式运行,然后使用这些行为。

像这样的代码应该在不同支持的浏览器上优雅地降级,或者让你利用浏览器特定的扩展,例如。

if (event.initKeyEvent)
{
    //gecko 1.9+
    event.initKeyEvent(...)
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题