شرح صفوف ومحتوى الفقرة
يُتفق هندسياً على تسمية دوال البناء بأسلوب الحرف الأول الكبير (PascalCase مثل Product) لتنبيه المطور إلى ضرورة استدعائها بالمعامل new. وعند تنفيذ new Product("SSD", 89) ينشئ المحرك تلقائياً كائناً فارغاً ويربط this به وينفذ الأسطر ثم يرجعه دون الحاجة لكتابة return.
JavaScript
function CourseItem(title, hours) {
if (!new.target) {
throw new TypeError('Call CourseItem with new');
}
this.title = title;
this.hours = hours;
}
const c1 = new CourseItem('ES6 Mastery', 14);
const c2 = new CourseItem('DOM Architecture', 18);
document.getElementById('ctor-out').textContent =
`${c1.title} (${c1.hours}h) | ${c2.title} (${c2.hours}h)`;