0

Error

Uncaught TypeError: Cannot call method 'appendChild' of undefined 

I was wondering if anyone can help me out, I was able to successfully implement inheritance using the Prototypal pattern, but when I try to code it using the Pseudo-classical (shown below) pattern - I Keep failing.

Can anyone direct me as to what I am doing wrong? Also what are the best practices when in comes to implementing inheritance in JavaScript?

Thanks in advance.

+ function test() {

    var obj = function(objType, objClass) {
        this.objType = objType;
        this.objClass = objClass;
    };

    obj.prototype.objCreate = function(objWidth, objHeight, objBackground) {
        this.element = document.createElement(obj.objType);
        document.getElementsByName('body')[0].appendChild(this.element);
        this.element.className = this.objClass;
        this.element.style.width = objWidth;
        this.element.style.height = objHeight;
        this.element.style.backgroundColor = objBackground;
    };

    var box1 = new obj('div', 'box1');

    box1.objCreate('200px', '200px', 'red');

}();

1 Answers1

0

The syntax error you're getting is because you're using document.getElementsByName instead of document.getElementsByTagName as I mentioned in the comments.

As far as inheritance goes, the topic has been already extensively covered on this forum.. I'll direct you to:

Pseudo-classical vs. "The JavaScript way"
JavaScript Inheritance

Community
  • 1
  • 1
megawac
  • 10,953
  • 5
  • 40
  • 61