在javascript对象原型中找不到数组长度属性

时间:2012-06-02 14:30:02

标签: javascript

我正在尝试创建一个简单的javascript / html5画布引擎来支持我的动画(这主要是为了学习目的。)

发动机:

/* 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 */

简单的来电代码:

$(function(){
    var World = new BM.World("background_container",400,600);
    var layer1 = new World.Layer({bgcolor:"#ff0000"});
});

有人可以告诉我Layer定义中我做错了什么吗?我得到的错误是:Uncaught TypeError: Cannot read property 'length' of undefined

1 个答案:

答案 0 :(得分:1)

当您使用World.Layer关键字调用函数new时,在World.Layer内,this指的是从World.Layer.prototype继承的空对象,而不是到World

解决方案可以是定义一个函数BM.World.prototype.getLayer,它负责将必要的数据从BM.World实例传递给BM.World.prototype.Layer构造函数。

相关问题