什么是定义对象和在javascript中设置它的属性之间的区别

时间:2012-03-22 06:47:33

标签: javascript

我正在分配一个小型库并使其在JS中面向对象,一切都很顺利,直到我发送的对象没有被正确处理。 如果我这样做:

var foo = {};
foo.bar = barbar; //barbar is a variable
foo.bar2 = barbar2 //barbar2 is also a variable
//more stuff

该对象有效,但是如果我这样做:

var foo = { bar : barbar, 'bar2': barbar2 /*more stuff*/ }

库无法正确识别对象。

我发现这是我调试3小时后出现的奇怪错误的原因,我仍然无法相信这是原因。 有人知道为什么会这样吗?我需要在将来动态创建对象,我更喜欢第二种方法...

编辑:

我正在使用该对象将信息传递给另一个在画布中绘制内容的函数,例如:

var test = {};//
test.init_x = 0; // all this works no matter what method I use to set them
test.init_y = 0;
test.sourceFile = 'img/tiles.png';
test.tileWidth = 16;
test.tileHeight = 16; //still works
test.arrayTiles = array; // this is a very large array of numbers
// The above only works if its defined this way, i.e. not by test = {arrayTiles:array};

示例代码,这就是我正在创建的对象:

var test = {}
test.init_x = 0;
test.init_y = 0;
test.sourceFile = 'img/map/grid_tiles.png';
test.tileWidth = 16;
test.tileHeight = 16;
test.tile_offset_x = 1;
test.tile_offset_y = 1;
test.sourceTileCounts = 4096;
test.sourceTileAccross = 64;
test.tilesWide = 64;
test.tilesHigh = 64;
test.tilesArray = [];//large numbers array
test.physicsArray = phys;
test.zoneTilesWide = 8;
test.zoneTilesHigh = 8;
test.mapTiles = [];//large numbers array
test.decoration = [];//large numbers array
test.tilesArray = makeMapTilesArray(test.mapTiles, test.decoration);

上述功能确实有效,但下一个代码段没有:

function Map(map,tiles,decor,phys,tileSizeW,tileSizeH,totalTiles,tilesPerRow,tilesW,tilesH,zoneW,zoneH){//map
    this.mapTiles           = tiles;
    this.decoration         = decor;
    this.tilesArray         = [];
    this.physicsArray       = phys;
    this.canvas             = 0;
    this.ctx                = 0;
    this.init_x             = 0;
    this.init_y             = 0;
    this.sourceFile         = 'img/map/'+map+'.png';
    this.tileWidth          = tileSizeW;
    this.tileHeight         = tileSizeH;
    this.tile_offset_x      = 1;
    this.tile_ofset_y       = 1;
    this.sourceTileCounts   = totalTiles;
    this.sourceTileAcross   = tilesPerRow;
    this.tilesWide          = tilesW;
    this.tilesHigh          = tilesH;
    this.zoneTilesWide      = zoneW;
    this.zoneTilesHigh      = zoneH;
    this.tilesArray = makeMapTilesArray(tiles, decor);//this function does some byte shifting
}
var test = new Map('grid_tiles',mapTiles,decoration,physicsArray,16,16,4096,64,64,64,8,8);

为什么它不起作用?图书馆可以为这两者做些什么?

0 个答案:

没有答案