如何向对象添加上下文方法

时间:2013-05-16 16:30:59

标签: javascript canvas

我正在用画布制作数学图形库,之前我的方法是直接将方法添加到全局上下文原型中,因此

CanvasRenderingContext2D.prototype.point=function(x,y){
    this.fillRect(x,y,1,1);
};

然而,我发现这不是推荐的,所以我现在正在尝试制作一个全局对象,因此

window.Graph=function(context){
    this.ctx=context;
    alert(this.ctx);
    this.CanvasRenderingContext2D.prototype.point=function(x,y){
        this.ctx.fillRect(x,y,1,1);
    };
};

我也试过

this.ctx.prototype.point=function(x,y){
        this.ctx.fillRect(x,y,1,1);
};

所有这些都会返回cannot set property 'point' to undefined

等错误

调用它的理想方式是

var g=new Graph(ctx);
g.point(5,5);

最好的方法是什么?

由于

2 个答案:

答案 0 :(得分:3)

以下是您要找的内容:

function Graph(context) {
    this.context = context;
}

Graph.prototype.point = function (x, y) {
    this.context.fillRect(x, y ,1, 1);
}

var g = new Graph(context);
g.point(5, 5);

答案 1 :(得分:2)

plalx展示了一个很棒的设计模式......

这是另一个带有构造函数的东西:

var Graph = (function () {

    // constructor
    function Graph(context) {

        // "class" properties go here
        this.context = context;
    }

    // "class" methods added to prototype here
    Graph.prototype.point = function (x,y) {
        this.context.fillRect(x,y,1,1);
    };

    // return a self reference
    return Graph;

})();    // make class available by self-executing

// instantiate your Graph class into a graph object
var graph = new Graph(context);
相关问题