Search code examples
javascriptprototype

javascript prototype definition error


I have this function(class) which I define a prototype function.

function testit(t,l, w, h, c, p) {
    this.div;
    this.obj = { "top": t, "left": l, "width": w, "height": h, "color": c };
}

testit.prototype.showit = function () {
     this.div = $("<div />")
        .css({
            "position": "absolute",
            "top": this.obj.top,
            "left": this.obj.left,
            "width": this.obj.width,
            "height": this.obj.height,
            "border": "1px solid " + this.obj.color
        })
        .appendTo(p);
}

When running the following code -

var aa;

aa = new testit(100, 100, 100, 100, "#CCCCCC", "body");
aa.showit();

I get the following error -

Unhandled exception

What is wrong with the prototype definition ?


Solution

  • The code doesn't cause the error you've listed (see the snippet I added to your question), unless of course you have a global p variable that's not a string or DOM element, which case I suppose it could.

    It does have a different error: p is not defined at the point you use it. You need to remember p in the constructor (this.p = p; perhaps) and then use that property (this.p) when calling appendTo:

    function testit(t,l, w, h, c, p) {
        this.div;
        this.obj = { "top": t, "left": l, "width": w, "height": h, "color": c };
        this.p = p;
    }
    
    testit.prototype.showit = function () {
         this.div = $("<div />")
        .css({
            "position": "absolute",
            "top": this.obj.top,
            "left": this.obj.left,
            "width": this.obj.width,
            "height": this.obj.height,
            "border": "1px solid " + this.obj.color
        })
        .appendTo(this.p);
    }
    
    var aa;
    
    aa = new testit(100, 100, 100, 100, "#CCCCCC", "body");
    aa.showit();
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

    You'll also have to beware of this issue if you're calling showit in (say) an event callback.