javascript原型定义错误

时间:2018-03-04 16:51:02

标签: javascript prototype

我有这个函数(类),我定义了一个原型函数。

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);
}

运行以下代码时 -

var aa;

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

我收到以下错误 -

Unhandled exception

原型定义有什么问题?

1 个答案:

答案 0 :(得分:0)

代码不会导致您列出的错误(请参阅我在问题中添加的代码段),除非您有一个全球p变量不是字符串或DOM元素,我认为它可以。

确实存在不同错误:p未在您使用它时定义。您需要在构造函数中记住p(或许this.p = p;),然后在调用this.p时使用该属性(appendTo):

&#13;
&#13;
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();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

如果您在(比方说)事件回调中调用showit,您还必须小心this issue

相关问题