我正在尝试使用原型创建一个JavaScript库。唯一的问题是我可以让我的函数返回getContext,但是我不知道如何在原型中引用父函数。这似乎不起作用,所以我尝试创建一个全局变量来保存这个变量,但效果不大。所以我认为还有另外一个问题,我不知道从哪里开始。
function isometric(id) {
var about = { // Returned if no parameters
version: 1.0,
author: "Josh Lalonde"
};
if (id) {
if (window === this) {
return new _(id);
} // Window passed to function.
this.canvas = document.getElementById(id); // The canvas to draw on.
var ctx = canvas.getContext("2d");
return ctx; //
}
else {
return about; // Nothing passed.
}
}这是原型。
isometric.prototype = {
clear: function() { //Clean up
var ctx = this;
ctx.fillStyle = "#000";
ctx.fillRect(0, 0, isometric.width, isometric.height); // Draw a black canvas
}
};我对测试代码的引用如下:
var iso = new isometric('canvas');
iso.clear();Jsfiddle:http://jsfiddle.net/joshlalonde/r8e2U/8/
发布于 2014-06-15 20:17:33
您正在设置等距原型,但构造函数返回CanvasRenderingContext2D的一个实例。因此,未定义.clear()方法。您可以做的是将上下文保存为等距属性,然后从isometric.prototype中定义的方法中访问它。要访问这些方法,您必须在构造函数中返回
...
this.ctx = canvas.getContext("2d");
return this;原型:
clear:function() { //clean up
var ctx = this.ctx;
//Also change the following line (you were using isometric.width, which is not defined)
ctx.fillRect(0, 0, this.canvas.width, this.canvas.height); // Draw a black canvas通过这些更改,您的代码可以工作:http://jsfiddle.net/UtRLb/1/
https://stackoverflow.com/questions/24233555
复制相似问题