DEV Community

BekmuhammadDev
BekmuhammadDev

Posted on

1 1 1 1 1

constructor function /

  • constructor function

Qo'shimcha:

  • ebugger keyword

Konstruktor funksiyasi (constructor function) JavaScriptda obyektlar yaratish uchun ishlatiladigan maxsus funksiyadir.

Konstruktor Funksiya shu ko'rinishda yaratiladi:

function Car(make, model, year) {
    this.make = make;
    this.model = model;
    this.year = year;
}

Enter fullscreen mode Exit fullscreen mode

Bu yerda Car nomli konstruktor funksiyasi yaratilgan. Konstruktor funksiyasi yangi obyekt yaratish uchun ishlatiladi va odatda katta harf bilan boshlanadi.
Bu funksiyada make, model, va year parametrlar bo'lib, ular yangi yaratilayotgan obyektning xususiyatlarini ifodalaydi.

this kalit so'zi yangi yaratilayotgan obyektni bildiradi:
this Kalit so'zi:
this kalit so'zining qiymati funksiyani qanday chaqirganingizga bog'liq. Konstruktor funksiyalarida this yangi yaratilgan obyektga ishora qiladi. Metodlar ichida esa this metod chaqirilgan obyektga ishora qiladi.

Yangi obyekt yaratish:


let myCar = new Car('Toyota', 'Corolla', 2020);

Enter fullscreen mode Exit fullscreen mode

Bu yerda new kalit so'zi yordamida Car konstruktor funksiyasi chaqirilgan va yangi obyekt yaratilgan. Bu chaqiruv quyidagi vazifalarni bajaradi:

  • Yangi bo'sh obyekt yaratiladi.
  • Yaratilgan obyekt this konteks biriktiriladi.
  • Car funksiyasi this orqali yangi obyektni to'ldiradi: make, model, va year xususiyatlari Toyota, Corolla, va 2020 qiymatlarini oladi.
  • Konstruktor funksiyasi avtomatik ravishda yangi yaratilgan obyektni qaytaradi va myCar o'zgaruvchisiga biriktiriladi.

Obyekt hususiyatlarini cansolega chiqarish:

console.log(myCar.make); 

Enter fullscreen mode Exit fullscreen mode

Bu yerda myCar o'zgaruvchisi yaratilgandan so'ng, uning make xususiyatiga kirish uchun console.log orqali natijani chiqaramiz. Bu kod Toyota qiymatini konsolga chiqaradi, chunki myCar obyektining make xususiyati Toyotaga teng qilib belgilangan.

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay