Bird
من التحدي السابق: وظيفة الطيور () {لاحظ أن المشغل
this.name = "Albert"؛
this.color = "blue"؛
this.numLegs = 2 ،
// "هذا" داخل المنشئ يشير دائمًا إلى الكائن الذي يتم إنشاؤه
}
واسمحوا blueBird = الطيور الجديدة () ؛
new
يستخدم عند استدعاء منشئ. هذا يخبر JavaScript لإنشاء instance
جديد من Bird
باسم blueBird
. بدون المشغل new
، لا يشير this
داخل المُنشئ إلى الكائن الذي تم إنشاؤه حديثًا ، مما يعطي نتائج غير متوقعة. الآن blueBird
لديه كل الخصائص التي تم تعريفها داخل منشئ Bird
: blueBird.name. // => ألبرتتمامًا مثل أي كائن آخر ، يمكن الوصول إلى خصائصه وتعديلها:
blueBird.color. // => أزرق
blueBird.numLegs. // => 2
blueBird.name = 'Elvira' ،
blueBird.name. // => إلفيرا
hound
باستخدام منشئ Dog
.
testString: 'assert(hound instanceof Dog, "hound
should be created using the Dog
constructor.");'
- text: يجب أن تستخدم شفرتك المشغل new
لإنشاء instance
Dog
.
testString: 'assert(code.match(/new/g), "Your code should use the new
operator to create an instance
of Dog
.");'
```