2011-03-26 72 views
0

我试图运行这个命令:约翰Resig的继承和Canvas .getContext

var Engine = Class.extend({ 
    canvas_id: 'canvas', 
    canvas: '', 
    context: '', 
    init: function(canvas_id) { 
     console.log('init: Setting this.canvas_id to ' + canvas_id); 
     this.canvas_id = canvas_id; 
    }, 
    begin: function() { 
     console.log('begin: Getting element with ID ' + this.canvas_id); 
     this.canvas = document.getElementById(this.canvas_id); 
     console.log(this.canvas_id); 
     console.log('begin: Set this.canvas', this.canvas) 
     this.context = this.canvas.getContext('2d'); 
     this.context.fillText("Hello World!", 10, 10); 
    } 
}); 

但在控制台中看到的错误:

init: Setting this.canvas_id to canvas 
begin: Getting element with ID canvas 
canvas 
begin: Set this.canvas null 
> Uncaught TypeError: Cannot call method 'getContext' of null < 

如何解决这个错误?

+2

您是使用'new Engine()'还是直接调用函数? – alex 2011-03-26 15:11:47

+0

是的, var engine = new Engine(“canvas”); engine.begin(); – vyu 2011-03-26 15:34:42

+0

我认为标题中的“John Resig Inheritance”与本文相关吗? http://ejohn.org/blog/simple-javascript-inheritance/ – 2011-03-26 15:37:47

回答

0

我认为这可能与你的情况和你使用'this'的canvas范围有关。在John Resig的例子中,这些属性都是属于该类的原始类型。但是,标记中的实际画布对象不属于您的类实例。

您是否尝试从画布和上下文中移除“this”?