AppendChild不工作!,从DOM元素对象继承.我做错了什么?

AppendChild does not work!,inheriting from DOM Element object..What Am I doing wrong here?

本文关键字:继承 错了 什么 对象 元素 工作 DOM AppendChild      更新时间:2023-09-26

我正在编写我的自定义元素,它比标准DOM元素有更多的方法,这里是继承自element对象的元素

function MyObject(){
    return (Object.create(document.createElement("Mytag"),{
         myfunction:function(){
             return blahblah;
         }
    }));
}//function for creating object ends
function MyObject2(){
    return (Object.create(document.createElement("Mytag2"),{
        myfunction:function(){
            return blahblah;
        }
    }));
}//function for creating second object ends
var a=new MyObject();//statement works fine
var b=new MyObject2();//statement works fine 

现在,当我试图使其中一个对象成为另一个对象的子对象时,我得到任何东西都可以工作,而不是抛出异常

a.appendChild(b);

因为您使用return (Object.create(...));,您的new MyObject();new MyObject2();返回对象而不是DOM元素,因此a.appendChild(b)将不起作用,因为ab预计是DOM元素。

要查看差异,请查看此jsFiddle

中的控制台

您需要将属性描述符传递给Object.create,而不是方法。

function MyObject() {
    return Object.create(document.createElement("Mytag"), {
        myfunction: {
            value: function() {
                 return 'blahblah';
            }
        }
    });
}

这在Chrome中为我工作:

a = new MyObject();
> HTMLUnknownElement {spellcheck: true, isContentEditable: false, contentEditable:
  "inherit", children: HTMLCollection[0], outerText: ""…}
a.myfunction()
> "blahblah"
但是请注意,不是正确地将对象的"类型"设置为MyObject。当我尝试将对象添加到DOM时,它也不能防止抛出异常: