0

私は自分のキャンバスに小さなフレームワークをセットアップしているだけで、Prototype はあまり使用していませんが、1 つだけ小さな問題があり、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

0

特別な理由がない限り、コードをこのようにフォーマットするだけで十分です。プロトタイプ create を関数に割り当てるだけで、「クラス」が初期化を実行できるようになります (これがより良い方法です)。

コードをよりシンプルで読みやすくします。

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 に答える