Inheriting from the DOM Element object in javascript ! Whats wrong with this code? -
i trying inherit dom element object,all code runs fine when create object when try call appendchild() method ,it gives error saying :
myobject doesn't have appendchild method
here code:
var content=document.createtextnode("this dynamically created"); function myobject(tagname){ element.constructor.call(this,tagname); this.prototype=element.prototype; this.prototype=object.defineproperties(this.prototype,{ newmethod:function(){ //dosomething } }); } var newobj=new myobject("div"); newobj.appendchild(content);
though you're doing incorrectly (more on later), you're trying pass object inherits dom element instead of dom element itself. not allowed.
it seems should work, dom elements , dom methods host objects. don't play same rules you'd expect native objects. .appendchild()
method wants element, , nothing else. you're trying won't work.
with respect approach inheritance, it's entirely incorrect. don't modify .prototype
property of new object being created. modify .prototype
of constructor function. it's done once, , new objects created constructor inherit object assigned constructor's .prototype
property.
because there's no inheritance way have it, there's no .appendchild()
method. code below fixes it, it'll still not work because of reason given above.
function myobject(tagname){ element.call(this, tagname); } myobject.prototype=object.create(element.prototype); object.defineproperties(myobject.prototype,{ newmethod: { value:function(){ //dosomething } } });
your property descriptor syntax wrong, fixed it.
Comments
Post a Comment