--- title: المنشئ (constructor) slug: Web/JavaScript/Reference/Classes/constructor tags: - جافاسكريبت translation_of: Web/JavaScript/Reference/Classes/constructor ---
الـ constructor
هي ميثود خاصة لإنشاء وتهيئة الاوبجكت(كائن) داخل (فئة)class
.
constructor([arguments]) { ... }
يمكننا إستخدام تلك الميثود لمرة واحده فقط ، وفي حال إستخدمنا constructor
ﻷكثر من مرة في نفس الفئة الـ class سيحدث {{jsxref("SyntaxError")}} إيرور .
A constructor can use the super
keyword to call the constructor of a parent class.
إذا لم تحدد ميثود إنشاء سيتم تحديد منشئ بشكل تلقائي.
If you do not specify a constructor method, a default constructor is used.
constructor
ذلك الكود تم أخذه ولصقة من classes sample (live demo)
class Square extends Polygon { constructor(length) { // Here, it calls the parent class' constructor with lengths // provided for the Polygon's width and height super(length, length); // Note: In derived classes, super() must be called before you // can use 'this'. Leaving this out will cause a reference error. this.name = 'Square'; } get area() { return this.height * this.width; } set area(value) { this.area = value; } }
إنظر إلى ذلك الكود
class Polygon { constructor() { this.name = "Polygon"; } } class Square extends Polygon { constructor() { super(); } } class Rectangle {} Object.setPrototypeOf(Square.prototype, Rectangle.prototype); console.log(Object.getPrototypeOf(Square.prototype) === Polygon.prototype); //false console.log(Object.getPrototypeOf(Square.prototype) === Rectangle.prototype); //true let newInstance = new Square(); console.log(newInstance.name); //Polygon
هنا البروتوتيب فئة الـ Square تغيرت ولكن الكونستركتور (المنشئ) مبني على فئة الـPolygon والتي تطلب عندما نقوم بإنشاء حالة مماثلة للـ Square مرة أخرى
ذكرنا سابقا أنه في حال عدم تحديدك لكونستركتور (منشئ) سيتم تحديد الكونستركتور بشكل إفتراضي ، وبالنسبة للكلاسز (الفئات) الاولية يكون الكونستركتور الخاص بها كما يلي :-
constructor() {}
أما الفئات المشتقة فتكون بالشكل التالي
constructor(...args) { super(...args); }
Specification | Status | Comment |
---|---|---|
{{SpecName('ES2015', '#sec-static-semantics-constructormethod', 'Constructor Method')}} | {{Spec2('ES2015')}} | Initial definition. |
{{SpecName('ESDraft', '#sec-static-semantics-constructormethod', 'Constructor Method')}} | {{Spec2('ESDraft')}} |
{{Compat("javascript.classes.constructor")}}