问题描述:

I am trying to create a simple javascript/html5 canvas engine to support my animation(this is mainly for learning purposes.)

Engine:

/* BOF GLOBAL REFERENCES*/

var BM = BM || {};

/* EOF GLOBAL REFERENCES */

/* BOF GLOBAL VARIABLES */

/* EOF GLOBAL VARIABLES */

/* BOF FUNCTIONS */

BM.World = function(container,width,height,name){

this.container = $("#"+container);

this.width = width;

this.height = height;

this.name = name || "DefaultWorld";

this.layers = new Array();

}

BM.World.prototype.Layer = function(options){

var options = options || {};

options.bgcolor = options.bgcolor || "transparent";

this.container.html( "<canvas id='"+this.name+"_layer_"+this.layers.length+"' style='position:absolute;top:0;left:0;width:"+this.width+";height:"+this.height+";background:"+options.bgcolor+";'>"

+"</canvas>");

}

/* EOF FUNCTIONS */

And the simple caller code:

$(function(){

var World = new BM.World("background_container",400,600);

var layer1 = new World.Layer({bgcolor:"#ff0000"});

});

Can someone please tell me what I am doing wrong in the Layer definition? the error I get is:Uncaught TypeError: Cannot read property 'length' of undefined

网友答案:

When you call the function World.Layer with the new keyword, then inside World.Layer, this refers to an empty object inheriting from World.Layer.prototype, and not to World.

A solution could be to define a function BM.World.prototype.getLayer which takes care of passing the necessary data from the BM.World instance to the BM.World.prototype.Layer constructor.

相关阅读:
Top