Object.create
Object.create ile var olan bir prototipi kullanarak nesne oluşturmayı öğrenirsin.
Object.create
Object.create(proto), parametre olarak verdiğin prototiple yeni bir nesne üretir. Üretilen nesne, proto'daki tüm özelliklere erişebilir.
const animalProto = {
describe() { return 'bir hayvanım'; }
};
const rex = Object.create(animalProto);
rex.describe(); // 'bir hayvanım'rex'in kendi describe özelliği yoktur; prototip zincirinden gelir. Bu, new kullanmadan prototip tabanlı kurulum yapmanın temel yoludur.
İkinci parametre ile kendi özellik
Object.create'in ikinci parametresi, yeni nesnenin kendi özelliklerini tanımlar. Her özellik bir tanımlayıcı (descriptor) nesnesi olarak yazılır.
const rex = Object.create(animalProto, {
name: { value: 'Rex', enumerable: true }
});Burada rex hem animalProto'dan gelen describe metodunu kullanır hem de kendi name özelliğine sahiptir. İkinci parametre opsiyoneldir; çoğunlukla boş bırakılır.
Uygulama animalProto ve rex'i Object.create ile kur
animalProto adında bir nesne tanımla; describe metodu 'bir hayvanım' döndürsün. rex'i Object.create(animalProto) ile üret. console.log(rex.describe()) ile prototipten gelen metodu çağır.
Örnek çözümü göster
const animalProto = {
describe() {
return 'bir hayvanım';
}
};
const rex = Object.create(animalProto);
console.log(rex.describe());
Kendini test et
-
Object.create(null) ne üretir?
- Object.prototype'ı prototip alan bir nesne
- Boş bir dizi
- Prototipi olmayan bir nesne
- null değerinde bir değişken
Cevabı göster
Prototipi olmayan bir nesne — Doğru! Object.create(null) prototipsiz bir nesne verir.
-
Object.create çağrısını tamamla
const rex = Object.____;Cevabı göster
const rex = Object.create(animalProto); -
Oluşturma desenlerini sonuçlarıyla eşleştir
- Object.create(proto)
- yeni nesne + prototip
- new Constructor()
- constructor + prototip
- {}
- Object.prototype
- Object.create(null)
- prototipsiz nesne