يعني إيه؟
زي النسخ واللصق في البرامج! 📋
بدل ما تعمل Object جديد من الصفر - انسخ واحد موجود! 🧬
الـ Object الأصلي اللي عنده method clone() - بيعرف ينسخ نفسه!
الـ Method اللي بتعمل نسخة كاملة من الـ Object - Deep Copy مش Reference!
أسرع من new خصوصاً لو الـ Object معقد ومحتاج setup كتير!
class Shape {
constructor(color, x, y) {
this.color = color;
this.x = x;
this.y = y;
}
// 🧬 Clone method - Deep Copy!
clone() {
// Object.assign for shallow copy
// For nested objects, use structuredClone()
return Object.assign(
Object.create(Object.getPrototypeOf(this)),
this
);
}
draw() {
return `Drawing ${this.color} shape at (${this.x}, ${this.y})`;
}
}
class Circle extends Shape {
constructor(color, x, y, radius) {
super(color, x, y);
this.radius = radius;
}
draw() {
return `⭕ ${this.color} circle r=${this.radius} at (${this.x}, ${this.y})`;
}
}
// 🎯 Create original prototype
const blueCircle = new Circle('blue', 10, 20, 50);
console.log(blueCircle.draw());
// ⭕ blue circle r=50 at (10, 20)
// 🧬 Clone instead of new!
const redCircle = blueCircle.clone();
redCircle.color = 'red'; // Just change what you need!
redCircle.x = 100;
console.log(redCircle.draw());
// ⭕ red circle r=50 at (100, 20)
// ✅ They are separate objects!
console.log(blueCircle === redCircle); // false
// 🚀 Useful for expensive objects
const expensiveObject = {
data: loadFromDatabase(), // Expensive!
cache: buildCache(), // Expensive!
config: parseConfig() // Expensive!
};
// Just clone when you need another one!
const copy = Object.assign({}, expensiveObject);
الشكل الأصلي - اضغط Clone!
bullets, enemies, particles - بنعمل clone بدل new!
إعدادات معقدة - ننسخها ونعدل الفرق بس!
Records متشابهة - clone أسرع من query جديد!
Components متشابهة - ننسخها بدل ما نبنيها!