javascript:Object.prototype.spoof=function(){if (this instanceof String){return '(new String("'+this.replace(/"/g, '\\"')+'"))';}var str=(this instanceof Array)? '[': (this instanceof Object)? '{': '(';for (var i in this){if (this[i] != Object.prototype.spoof) {if (this instanceof Array == false) {str+=(i.match(/\W/))? '"'+i.replace('"', '\\"')+'":': i+':';}if (typeof this[i] == 'string'){str+='"'+this[i].replace('"', '\\"');}else if (this[i] instanceof Date){str+='new Date("'+this[i].toGMTString()+'")';}else if (this[i] instanceof Array || this[i] instanceof Object){str+=this[i].spoof();}else {str+=this[i];}str+=', ';}};str=/* fix */(str.length>2?str.substring(0, str.length-2):str)/* -ed */+((this instanceof Array)? ']': (this instanceof Object)? '}': ')');return str;};for(i in objRA=[[ 'Simple Raw Object source code:','[new Array, new Object, new Boolean, new Number, ' +'new String, new RegExp, new Function, new Date]' ] ,
[ 'Literal Instances source code:','[ [], {}, true, 1, "", /./, function(){}, new Date() ]' ] ,
[ 'some predefined entities:','[JSON, Math, null, Infinity, NaN, ' +'void(0), Function, Array, Object, undefined]' ]])alert(['\n\n\ntesting:',objRA[i][0],objRA[i][1],'\n.toSource()',(obj=eval(objRA[i][1])).toSource(),'\ntoSource() spoof:',obj.spoof()].join('\n'));
其中显示:
testing:Simple Raw Object source code:[new Array, new Object, new Boolean, new Number, new String,new RegExp, new Function, new Date]
.toSource()[[], {}, (new Boolean(false)), (new Number(0)), (new String("")),/(?:)/, (function anonymous() {}), (new Date(1303248037722))]
toSource() spoof:[[], {}, {}, {}, (new String("")),{}, {}, new Date("Tue, 19 Apr 2011 21:20:37 GMT")]
//Make an object a string that evaluates to an equivalent object// Note that eval() seems tricky and sometimes you have to do// something like eval("a = " + yourString), then use the value// of a.//// Also this leaves extra commas after everything, but JavaScript// ignores them.function convertToText(obj) {//create an array that will later be joined into a string.var string = [];
//is object// Both arrays and objects seem to return "object"// when typeof(obj) is applied to them. So instead// I am checking to see if they have the property// join, which normal objects don't have but// arrays do.if (typeof(obj) == "object" && (obj.join == undefined)) {string.push("{");for (prop in obj) {string.push(prop, ": ", convertToText(obj[prop]), ",");};string.push("}");
//is array} else if (typeof(obj) == "object" && !(obj.join == undefined)) {string.push("[")for(prop in obj) {string.push(convertToText(obj[prop]), ",");}string.push("]")
//is function} else if (typeof(obj) == "function") {string.push(obj.toString())
//all other values can be done with JSON.stringify} else {string.push(JSON.stringify(obj))}
return string.join("")}