Javascript 如何使用prototype继承变量?

Javascript 如何使用prototype继承变量?,javascript,Javascript,我只是为我的画布设置了一个小框架,我没有经常使用原型,但它看起来非常棒,只是有一个小问题,create函数没有从新的函数继承宽度和高度,我该怎么做?代码: function CtxCanvas() { this.fps = undefined; this.width = undefined; this.height = undefined; } CtxCanvas.prototype = { constructor: CtxCanvas, new

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

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

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

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

这样格式化代码就足够了,除非有特殊原因不这样做。 您可以简单地将原型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);

new
函数中放入的任何内容都应该放在构造函数本身中。此外,您不需要指定
构造函数
属性,这是内置的。将属性初始化为
未定义
(除非您在obj检查中使用
'prop',这是不太可能的)。访问
obj.undefinedProperty
无论如何都会产生
undefined
。如果我这样做
CtxCanvas.new(30,1000,1000).create()我得到未定义的不是一个函数,知道为什么吗?不要这样做。使用
新的CtxCanvas(30,1000,1000)
谢谢你的帮助,但是为什么会出现错误呢?如果原型上有
new
,它将可用于CtxCanvas实例,而不是CtxCanvas本身
new CtxCanvas().new()
存在,但
CtxCanvas.new
未定义(因此不是函数)。