الـ constructor
هي ميثود خاصة لإنشاء وتهيئة الاوبجكت(كائن) داخل (فئة)class
.
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
بناء الجملة
constructor([arguments]) { ... }
الوصف
يمكننا إستخدام تلك الميثود لمرة واحده فقط ، وفي حال إستخدمنا constructor
ﻷكثر من مرة في نفس الفئة الـ class سيحدث 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);
}
Specifications
Specification | Status | Comment |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Constructor Method' in that specification. |
Standard | Initial definition. |
ECMAScript (ECMA-262) The definition of 'Constructor Method' in that specification. |
Living Standard |
دعم المتصفحات
BCD tables only load in the browser