JS重写Object的toString()方法,objecttostring
分享于 点击 11376 次 点评:35
JS重写Object的toString()方法,objecttostring
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>
相关文章
- 暂无相关文章
用户点评