الهدف التعليمي

التعرف على كيفية إنشاء Functions مُنشئة (Constructor Functions) في JavaScript لبناء Objects متعددة ذات خصائص وأساليب متشابهة.

عرض تطبيقي

الشرح البرمجي


// Constructor Function
function User(name, age, email) {
    this.name = name;
    this.age = age;
    this.email = email;

    this.greet = function() {
        return `مرحبًا ${this.name}! عمرك ${this.age} عامًا وبريدك الإلكتروني هو ${this.email}.`;
    };

    this.updateName = function(newName) {
        this.name = newName;
    };
}

// Users Data
const users = [
    new User("أسامة", 25, "osama@example.com"),
    new User("سما", 30, "sama@example.com")
];

// Rendering Users
function renderUsers() {
    const userContainer = document.getElementById("userContainer");
    userContainer.innerHTML = "";

    users.forEach(user => {
        const userDiv = document.createElement("div");
        userDiv.className = "user-card";
        userDiv.innerHTML = `
            

${user.greet()}

`; userContainer.appendChild(userDiv); }); } // Updating User Name function updateUserName(currentName) { const newName = prompt(`أدخل الاسم الجديد للمستخدم ${currentName}:`); if (newName) { const user = users.find(u => u.name === currentName); user.updateName(newName); alert("\u062A\u0645 \u062A\u062D\u062F\u064A\u062B \u0627\u0644\u0627\u0633\u0645 \u0628\u0646\u062C\u0627\u062D!"); renderUsers(); } } // Initial Render renderUsers();