1. 程式人生 > >JS重寫Object的toString()方法

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>