我只是为我的画布设置一个小框架,我没有经常使用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();
答案 0 :(得分:1)
您的构造函数是初始化对象的函数,您的new
函数永远不会被调用:
function CtxCanvas(f, w, h) {
this.fps = f;
this.width = w;
this.height = h;
}
答案 1 :(得分:0)
像这样格式化代码就足够了,除非有特殊原因不这样做。 您可以简单地将原型create分配给一个函数,并允许'class'进行初始化(这是更好的方法)。
使您的代码更简单,更易读。
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);