新创建的CustomEvent没有自己的属性(“类型”),因此jQuery失败了吗?

时间:2019-10-06 22:04:35

标签: javascript jquery

我在一个非常基础的类上工作,该类使用(非常)私有事件。

由于我不希望此类依赖于jQuery,因此我使用普通的CustomEvent(尽管我使用jQuery)

惊喜之一是当jQuery触发我的事件失败时,令人惊讶的2是jQuery在CustomEvent上测试hasOwnProperty("type"),这是FALSE

简而言之:(编辑:JunctionEvent误导了-它只是一个字符串“ ju-ac”-所以我在示例中将其更改了)

    junctionevent = "ju-ac"

    e = new CustomEvent(junctionevent, {bubbles: options.bubbles, composed: true})
    console.log e, e.type, e.hasOwnProperty("type")

says(“ ju-ac”是此开发阶段中事件的名称或类型):

ju-ac { target: null, isTrusted: false, eventPhase: 0, bubbles: true, cancelable: false, returnValue: true, defaultPrevented: false, composed: true, timeStamp: 9808, cancelBubble: false, … }
 ju-ac 
 false

因此,该事件具有“属性”类型,名称为“ ju-ac”,但没有名为type的属性吗?

我怎么了? (或者jQuery在做什么错?)

编辑:我刚刚了解到,jQuery无法将普通的CustomEvents作为事件输入处理,它会像事件数据一样处理这些事件数据(就像输入中的任何其他对象一样)-我敢打赌。 这不会改变我的问题:为什么在创建具有字符串“ xxxx”的属性type之后出现事件,但是hasOwnProperty(“ type”)返回FALSE

1 个答案:

答案 0 :(得分:1)

之所以在新创建的CustomEvent实例中看到属性type,而同时使用false方法调用时却得到hasOwnProperty('type')是因为type属性是通过原型链从Event对象继承的属性,而不是新创建的实例直接拥有的属性。

因此,实例e从其构造函数CustomEvent继承属性,而CustomEvent从其自己的构造函数Event对象继承属性,type是对象的所有者Event属性。

您可以一直遵循原型链,一直到hasOwnProperty("type")对象,然后查看let e = new CustomEvent("ju-ac"); e.type; // "ju-ac"; e.hasOwnProperty("type"); // false // One step deep into the prototype chain e.__proto__.constructor; // CustomEvent e.__proto__.hasOwnProperty("type"); // false // Two steps deeper into the prototype chain e.__proto__.__proto__.constructor; // Event e.__proto__.__proto__.hasOwnProperty("type"); // true 如何返回true,如下所示:

{{1}}

事件:“ CustomEvent,我是你的父亲!”

CustomEvent:“不!”