JS重写Object的toString()方法

1. 起因:JSON.stringify方法转换成的字符串为JSON格式,属性名带有双引号,input输入框提交时报错。原因待确认。

2. 

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		
		<script type="text/javascript">
			
			Object.prototype.toString = function() {
				var str = '{'
				for(var tmp in this) {
					if(typeof this[tmp] === 'object')
						str += tmp + ':' + this[tmp] + ','
					else
						str += tmp + ':"' + this[tmp] + '",'
				}
				return str + '}'
			}
			
			var o = {
				a: '1',
				b: {
					c: '1',
					d: {
						e: '1'
					}
				}
			}
			
			console.log(o)	//"{a:"1",b:{c:"1",d:{e:"1",},},}"
			
			eval('var o2 = ' + o)
			
			console.log(o2)	//"{a:"1",b:{c:"1",d:{e:"1",},},}"
			
		</script>
		
	</body>
</html>


版权声明:本文为guoxiaozhuang4原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。