G
George
Functions are objects and as such inherit from Object.prototype.
I've tested this in Safari 4, it (sort-of) works
//Load the JSON lib
if (!JSON) {
document.body.appendChild(
document.createElement(
'script')).src="http://www.JSON.org/json2.js";
}
delete Object.prototype.toSource;
if (!Object.prototype.toSource && JSON && JSON.stringify) {
Object.prototype.toSource= function (txt) {
function replacer (key, value, n) {
if (typeof value === "function") {
n= !((value.name === "") || (value.name === "anonymous"));
value= "***FuNcTiOn"+ (n?"":"(")+ value+ (n?"":")")+
"nOiTcNuF***";
}
return value;
}
txt= JSON.stringify(this, replacer)
return txt.replace(/("\*\*\*FuNcTiOn)|(nOiTcNuF\*\*\*")/g,"");
};
}
function zero () { return 0; }
var identity = new Function('x', 'return x;');
var obj= { a:1, f:function (_a) { a=_a; } };
var arr = [1, 2, function () { } ];
alert(zero.toSource());
// return function zero() { return 0; }
alert(identity.toSource());
// return (function anonymous(x) {return x;})
alert(obj.toSource());
// return ({a:1, ffunction (_a) {a = _a;})})
alert(arr.toSource());
// return [1, 2, (function () { } )]
HI Jorge,
When I try your code, I found a slight issue need to fix, as below.
var problematicFun1 = new Function('x', 'return x+"\n"');
var problematicFun2 = new Function('x', 'return x');
alert(problematicFun1.toSource()); // this cause an error
alert(problematicFun1.toSource()); // this works, but how can I get
rid of the trailing '\n's.
Thanks,
Yan