简体   繁体   中英

How do I inherit a variable with prototype?

I'm just setting up a little framework for my canvas, I haven't used Prototype a lot, but it seems to be pretty damn awesome, just having one little problem, the create function is not inheriting the width and height from the new function, how might I do this? Code:

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

Your constructor function is what initializes the object, your new function never gets called:

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

It is sufficient to format your code like this, unless there's a special reason not to. You can simply assign the prototype create, to a function, and allow the 'class' to do the initialization (which is the better approach).

Makes your code simpler and more readable.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM