0

我只是为我的画布设置了一个小框架,我没有经常使用 Prototype,但它似乎非常棒,只是有一个小问题,create函数没有从new函数继承宽度和高度,我该怎么做?代码:

function CtxCanvas() {
    this.fps    = undefined;
    this.width  = undefined;
    this.height = undefined;
}

CtxCanvas.prototype = {
    constructor: CtxCanvas,
    new: function(fps, width, height) {
        this.fps    = fps;
        this.width  = width;
        this.height = height;
    },
    create: function() {
        var df = document.createDocumentFragment()
          , canvasElement = document.createElement('canvas');
        canvasElement.width = this.width;
        canvasElement.height = this.height;
        df.appendChild(canvasElement);
        document.getElementsByTagName('body')[0].appendChild(df);

        return canvasElement.getContext('2d');
    }
}
var ctx = new CtxCanvas(30, 1000, 1000).create();
4

2 回答 2

1

您的构造函数是初始化对象的函数,您的new函数永远不会被调用:

function CtxCanvas(f, w, h) {
    this.fps    = f;
    this.width  = w;
    this.height = h;
}
于 2013-04-28T00:29:27.230 回答
0

像这样格式化您的代码就足够了,除非有特殊原因不这样做。您可以简单地将原型创建分配给一个函数,并允许“类”进行初始化(这是更好的方法)。

使您的代码更简单,更具可读性。

function CtxCanvas(f, w, h) {
    this.fps    = f;
    this.width  = w;
    this.height = h;
}

CtxCanvas.prototype.create = function() {
    var df = document.createDocumentFragment()
    var canvasElement = document.createElement('canvas');
    canvasElement.width = this.width;
    canvasElement.height = this.height;
    df.appendChild(canvasElement);
    document.getElementsByTagName('body')[0].appendChild(df);

    return canvasElement.getContext('2d');
};
var ctx = new CtxCanvas(30, 1000, 1000).create();
alert(ctx);
于 2013-04-28T00:50:36.840 回答