JavaScript Nesne Prototipleri
Tüm JavaScript nesneleri, bir prototipten özellikleri ve yöntemleri devralır.
Önceki bölümde bir nesne oluşturucunun nasıl kullanılacağını öğrendik :
Örnek
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
const myFather = new Person("John", "Doe", 50, "blue");
const myMother = new Person("Sally", "Rally", 48, "green");
Ayrıca mevcut bir nesne oluşturucuya yeni bir özellik ekleyemeyeceğinizi öğrendik :
Örnek
Person.nationality = "English";
Bir kurucuya yeni bir özellik eklemek için onu kurucu işlevine eklemelisiniz:
Örnek
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
this.nationality = "English";
}
Prototip Kalıtım
Tüm JavaScript nesneleri, bir prototipten özellikleri ve yöntemleri devralır:
Date
nesneler miras alırDate.prototype
Array
nesneler miras alırArray.prototype
Person
nesneler miras alırPerson.prototype
Prototip Object.prototype
miras zincirinin en üstündedir:
Date
nesneler, Array
nesneler ve Person
nesneler Object.prototype
.
Nesnelere Özellikler ve Yöntemler Ekleme
Bazen belirli bir türdeki tüm mevcut nesnelere yeni özellikler (veya yöntemler) eklemek istersiniz.
Bazen bir nesne oluşturucuya yeni özellikler (veya yöntemler) eklemek istersiniz.
Prototip Özelliğini Kullanma
JavaScript prototype
özelliği, nesne oluşturuculara yeni özellikler eklemenize olanak tanır:
Örnek
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
Person.prototype.nationality = "English";
JavaScript prototype
özelliği, nesne oluşturuculara yeni yöntemler eklemenize de olanak tanır:
Örnek
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
Person.prototype.name = function() {
return this.firstName + " " + this.lastName;
};
Yalnızca kendi prototiplerinizi değiştirin. Standart JavaScript nesnelerinin prototiplerini asla değiştirmeyin.