【发布时间】:2014-07-30 12:06:37
【问题描述】:
你好 StackOverflowers,
我正在为我的 Web 应用程序实现一个 LocalStorage 系统。
但我很遗憾的是,Model抽象层中的所有对象都必须序列化。
我知道当对象转换为 JSON 时,函数不会被序列化。
我正要使用Option 1 described here。 (也就是说,创建一个“静态”方法,该方法返回一个包含函数的全新对象)。
但是,问题是即使对象的非函数成员也没有被转换。
例如在 divvie.textContent = JSON.stringify(coffee); 处,divvie.textContent 变为“{}”。
为什么?这是怎么回事?
示例代码,不是我的真实应用程序,但情况大致相同: 检查咖啡
var coffee = new Coffee( "0001", "DE Red Coarse",
"Douwe Egberts, red & coarse grounded." );
coffee.addSugarCube( "0x0F_BROWN", "15" );
coffee.addSugarCube( "0x0C_WHITE", "12" );
var divvie = document.getElementById( "run" );
divvie.textContent = JSON.stringify( coffee );
</script>
</body>
</html>
/**
* @class This class represents a coffee.
*
* @param {String} id
* @param {String} name
* @param {String} description
* @returns {Coffee}
*/
function Coffee( id, name, description )
{
var sugarCubes = new Array();
var maxAmountOfSweetness = 0;
/**
* @returns {String}
*/
this.getId = function()
{
return id;
};
/**
* @returns {String}
*/
this.getName = function()
{
return name;
};
/**
* @returns {String}
*/
this.getDescription = function()
{
return description;
};
/**
* @param {String} sugarCubeId
* @param {Number} amountOfSweetness
*/
this.addSugarCube = function( sugarCubeId, amountOfSweetness )
{
/// First check if this sugarCube is already in our coffee.
var sugarCubeFound = false;
for( var i = 0; i < sugarCubes.length; i++ )
{
if( sugarCubes[ i ].getId() === sugarCubeId )
{
sugarCubeFound = true;
i = sugarCubes.length;
}
}
if( !sugarCubeFound )
{
/// Oh Sweet! A new sugar cube to add in our coffee!
sugarCubes.push( new SugarCube( sugarCubeId, amountOfSweetness ) );
maxAmountOfSweetness = Math.max( maxAmountOfSweetness, amountOfSweetness );
}
};
/**
* @param {String} sugarCubeId
* @returns {SugarCube}
*/
this.getSugarCube = function( sugarCubeId )
{
for( var i = 0; i < sugarCubes.length; i++ )
{
if( sugarCubes[ i ].getId() === sugarCubeId )
{
return sugarCubes[ i ];
}
}
};
/**
* @returns {Boolean} True when the amount of sugar cubes in this coffee is 1 or more,
* false when not.
*/
this.isSweet = function()
{
if( 0 < sugarCubes.length )
{
return true;
}
return false;
};
}
/**
* @class This class represents a sugar cube
*
* @param {String} id
* @param {Number} amountOfSweetness
* @returns {SugarCube}
*/
function SugarCube( id, amountOfSweetness )
{
/**
* @returns {String}
*/
this.getId = function()
{
return id;
};
/**
* @returns {Number}
*/
this.getAmountOfSweetness = function()
{
return amountOfSweetness;
};
}
【问题讨论】:
标签: javascript json serialization stringify