In questo articolo vedremo come clonare oggetti e array estendendo gli oggetti core Object e Array. La soluzione è pensata per quei browser che ancora non supportano le ultime novità introdotte da ECMAScript 5. Vediamola in dettaglio.
Il codice è il seguente:
Object.prototype._clone = function() {
var o = {};
for (var property in this) {
o[property] = typeof(this[property]) === 'object' ? this[property]._clone() : this[property];
}
return o;
}
Array.prototype._clone = function() {
var a = [];
for (var property in this) {
a[property] = typeof(this[property]) === 'object' ? this[property]._clone() : this[property];
}
return a;
}
Il metodo _clone()
applicato agli oggetti clona anche le proprietà ereditate tramite la catena dell'oggetto prototype
.
Per evitarlo possiamo utilizzare il metodo hasOwnProperty()
:
if(this.hasOwnProperty(this[property]) {
//...
}
Esempio d'uso:
var o1 = {
test: 'Test'
};
var clone1 = o1._clone();
console.log(clone1.test); // 'Test'
var a1 = ['a', 1];
var clone2 = a1._clone();
console.log(clone2[1]); // 1