根据我的阅读,javascript 中的嵌套函数会导致额外的声明/破坏,这可以通过使用“静态函数”甚至单例实现来避免。在函数或对象的两个实例也是独立副本的情况下,“新”也会做同样的事情。
这是真的?如果是这样,我该怎么做才能拥有与嵌套函数和“新”相同的功能。这适用于服务器位于 nodejs / javascript 中的游戏。我已经达到了大约 8 个级别的嵌套函数并且开始担心。
例子:
DB.cityUpdateUpkeep = function( cuid )
{
/** @type {Array} */
var buildings = null;
DB.cityGet( cuid, function( error, city )
{
if( error )
{
console.log( "Couldn't get city" );
}
else
{
DB.iBuildings.find( {cuid:cuid}, function( error, cursor )
{
if( error )
{
console.log( "-error:" );
console.log( error );
}
else
{
cursor.toArray( function( error, response )
{
if( error )
{
console.log( "-error:" );
console.log( error );
}
else
{
console.log( "-the response:" );
console.log( response );
buildings = response;
var income = city.resources.income;
var storage = city.resources.storage;
var stored = city.resources.stored;
for( var buildingID in buildings )
{
var building = buildings[ buildingID ];
var blueprint = DB.bBuildings[ building.buid ];
if( blueprint.resources.income )
{
income = Utils.sumObjects( income, blueprint.resources.income );
}
if( blueprint.resources.storage )
{
storage = Utils.sumObjects( storage, blueprint.resources.storage );
}
if( blueprint.resources.stored )
{
stored = Utils.sumObjects( stored, blueprint.resources.stored );
}
}
console.log( "cuid: " + city._id + " income: " + income + " storage " + storage + " stored " + stored );
}
});
}
});
}
});
};