是否可以使用 Object.create 模式来创建 CustomEvent 对象

Is it possible to use the Object.create pattern to create a CustomEvent object?

本文关键字:创建 CustomEvent 对象 模式 create 可以使 Object 是否      更新时间:2023-09-26

我知道你可以创建一个这样的CustomEvent

var wordCreated = new CustomEvent(
    "newWord", 
    {
        detail: {
            word: "hola",
            translation: "hi",
        },
        bubbles: true,
        cancelable: true
    }
);

我想知道如何在不使用new的情况下做到这一点,使用Object.create模式?

我没有看到解决方案的问题是CustomEvent有两个参数:一个指定事件名称的字符串,以及一个包含bubblescancelabledetails 属性的配置对象。我不确定如何将字符串和对象传递给Object.create.

最终,我希望能够以以下标准方式使用此自定义事件:

var p = document.querySelector('p'); // a random node
p.addEventListener('newWord', function(ev){ console.log(ev) });
p.dispatchEvent(wordCreated);

标题中"是否可以使用 Object.create 模式创建 CustomEvent 对象?"问题的答案是肯定的。现在,后续问题"你会那样做吗?"的答案可能是否定的。正如@MartinErnst指出的那样,你最终会重新发明new已经在做的事情的轮子。

newObject.create 之间的主要区别(如果您还不知道)Object.create创建了一个Object(注意大写 O),它继承了指定为 Object.create 的第一个参数的对象的原型。在返回指定对象的实例之前,new运算符对调用给定对象的构造函数的额外步骤执行相同的操作(请注意小写 o)。

因此,我们可以使用 Object.create 创建一个继承自CustomEvent原型的Object

,如下所示:
var customEvent1 = Object.create(CustomEvent, {  
                     detail: {
                        writable:true, 
                        configurable:true, 
                        value: { word:"hola", translation:"hi" }
                      },
                      bubbles: {
                        writable:true,  
                        configurable:true, 
                        value:true 
                      },
                      cancelable:  {
                        writable:true,  
                        configurable:true, 
                        value:true 
                      },
                      type: {
                        writable:true,
                        configurable:true,
                        value:'newWord'
                      }
                    });

但是做一个console.log(customEvent1)会产生一个Object

与此形成对比:

var customEvent2 = new CustomEvent("newWord", { 
                     detail: {
                      word: "hola",
                      translation: "hi",
                     },
                     bubbles: true,
                     cancelable: true
                   });

您将看到运行console.log(customEvent2);将产生 CustomEvent 的实例。

因此,当您尝试在上述customEvent1对象上调用addEventListener()dispatchEvent()时,它将失败,因为这是一个Object,而不是Event。还需要执行一些步骤才能将customEvent1转换为完整的Event对象,这基本上是new CustomEvent()已经在做的事情。

小提琴可用 这里.

我认为它应该是这样的:

obj.addEventListener("newWord", function(e) {alert(e.detail);});
var wordCreated = Object.create(CustomEvent.prototype, {
  "newWord": 
    {
        detail: {
            word: "hola",
            translation: "hi",
        },
        bubbles: true,
        cancelable: true
    }
});