Envoyé par
SpaceFrog
Sous IE :
Sous IE aussi ???
Quelle version ?
La méthode "toSource()" est normalement standard depuis javascript 1.3 SAUF sous Safari et un autre dont je n'ai plus souvenir... Bref !
Quelques solutions existent, j'en élabore une dont il me reste un(?) point à régler :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
if(!Object.toSource) {
Object.prototype.toSource = function () {
var selfCall = (this.toSource.caller != null) && (this.toSource.caller == this.toSource);
function _null (n) {return typeof n == 'object' ? 'null' : '(void 0)'}
switch(this.constructor) {
case Boolean:
return (selfCall) ? this : "(new Boolean("+this+"))";
case Number:
return (selfCall) ? this : "(new Number("+this+"))";
case String:
var s = '\"'+this.replace(/[\\\"\']/g,"\\$&")+'\"';
return (selfCall) ? s : "(new String(" + s + "))";
case Date:
return "(new Date("+this.valueOf()+"))";
case RegExp:
return "(new RegExp("+this+"))";
case Function:
return '('+this.toString().replace(/[\s]+/g,' ').replace(/{ /g,'{').replace(/ }/g,'}')+')';
case Array:
var a = [];
for (var i=0, n=this.length; i<n; i++) { a[i] = this[i]?this[i].toSource():_null(this[i]); }
return '['+a.toString()+']';
default:
var o = [];
for(var p in this) {
if (!this.hasOwnProperty(p)) continue;
o.push(p.valueOf()+':'+(this[p]?this[p].toSource():_null(this[p])));
}
return "({"+o.join(", ")+"})";
}
}
} |
Le point qu'il me reste à régler est que :
(new Array(5)).toSource()
donne :
Que je vais intercépter avec :
new RegExp(/^[,]+$/).test(this.toString())
Sinon, on peut voir des solutions de clonage ou de sérialisation.
Partager