From 8f2731905212f6e7eb2d9793ad20b8b448c54ccf Mon Sep 17 00:00:00 2001 From: Florian Merz Date: Thu, 11 Feb 2021 14:51:31 +0100 Subject: unslug tr: move --- .../control_flow_and_error_handling/index.html | 419 +++++++++++++ .../web/javascript/guide/fonksiyonlar/index.html | 662 --------------------- files/tr/web/javascript/guide/functions/index.html | 662 +++++++++++++++++++++ files/tr/web/javascript/guide/ifadeler/index.html | 419 ------------- .../index.html" | 504 ---------------- .../guide/working_with_objects/index.html | 504 ++++++++++++++++ 6 files changed, 1585 insertions(+), 1585 deletions(-) create mode 100644 files/tr/web/javascript/guide/control_flow_and_error_handling/index.html delete mode 100644 files/tr/web/javascript/guide/fonksiyonlar/index.html create mode 100644 files/tr/web/javascript/guide/functions/index.html delete mode 100644 files/tr/web/javascript/guide/ifadeler/index.html delete mode 100644 "files/tr/web/javascript/guide/nesneler_ile_\303\247al\304\261\305\237mak/index.html" create mode 100644 files/tr/web/javascript/guide/working_with_objects/index.html (limited to 'files/tr/web/javascript/guide') diff --git a/files/tr/web/javascript/guide/control_flow_and_error_handling/index.html b/files/tr/web/javascript/guide/control_flow_and_error_handling/index.html new file mode 100644 index 0000000000..dcf6d13466 --- /dev/null +++ b/files/tr/web/javascript/guide/control_flow_and_error_handling/index.html @@ -0,0 +1,419 @@ +--- +title: Kontrol akışı ve hata yakalama +slug: Web/JavaScript/Guide/Ifadeler +tags: + - Başlangıç + - JavaScript + - Rehberi +translation_of: Web/JavaScript/Guide/Control_flow_and_error_handling +--- +
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Grammar_and_types", "Web/JavaScript/Guide/Loops_and_iteration")}}
+ +

JavaScript, uygulamanızın etkilişim halinde olmasını sağlayan kontrol akışı ifadeleri gibi birçok ifadeyi destekler. Bu bölümde, bu ifadeler üzerine durulacaktır.

+ +

En basit olarak anlatmak gerekirse, JavaScript tarafından çalıştırılacak her komuta ifade adı verilir. Noktalı virgül (;) karakteri ise, JavaScript kodundaki ifadelerin birbirinden ayrılması için kullanılmaktadır.

+ +

Blok ifadesi

+ +

En temel ifade türü, ifadelerin gruplanmasını sağlayan blok ifadesidir. Blok ifadesi,  bir çift süslü parantezle sınırlandırılır:

+ +
{ ifade_1; ifade_2; . . . ifade_n; }
+
+ +

Örnek

+ +

Blok ifadeleri genellikle kontrol akışı ifadeleri ile birlikte kullanılır (örn: if, for, while).

+ +
while (x < 10) {
+  x++;
+}
+
+ +

Buradaki, { x++; } bir blok ifadesidir.

+ +

Önemli: ECMAScript2015'ten önceki JavaScript'te blok etki alanı bulunmamaktadır. Blok içerisinde yer alan değişkenlerin etki alanı, onları içeren fonksiyon veya .js dosyası kadar geniş bir alanı kapsar, ve bu değişkenler üzerinde yapılan değişiklikler bloğun ötesinde de kalıcılık gösterir. Başka bir deyişle blok ifadeleri, değişkenler için bir etki alanı oluşturmazlar. C ve Java dilinden aşina olduğunuz değişkenden bağımsız blok ifadeleri, JavaScript'te tamamıyla farklı bir davranış sergileyebilirler. Aşağıdaki örneği inceleyelim:

+ +
var x = 1;
+{
+  var x = 2;
+}
+console.log(x); // Ekrandaki çıktı: 2
+
+ +

Kodun çıktısı 2 olacaktır. Çünkü blok içerisindeki var x ifadesi  ile bloktan önce gelen var x ifadesi aynı etki alanı içerisindedir. Eğer üstteki kod C veya Java dilinde olsaydı, ekrandaki çıktı 1 olacaktı.

+ +

ECMAScript 6 ile birlikte gelen let tanımıyla oluşturulan değişkenler, blok seviyesinde etki alanına sahiptir. Daha fazla bilgi için {{jsxref("Statements/let", "let")}} sayfasına bakınız.

+ +

Koşullu ifadeler

+ +

Belirli bir koşul sağlandığında çalışacak komutlar kümesine koşullu ifade denilir. JavaScript, iki adet koşullu ifadeyi destekler: if...else ve switch.

+ +

if...else ifadesi

+ +

Belirli bir mantıksal durum sağlandığında bir ifadenin çalıştırılması için if ifadesi kullanılır. Mantıksal durum sağlanmadığında çalıştırılacak komutlar için ise else kelimesi kullanıılabilir. Bir if ifadesi aşağıdaki şekilde oluşturulur:

+ +
if (mantıksal_durum) {
+  ifade_1;
+} else {
+  ifade_2;
+}
+ +

mantıksal_durum, true veya false değerler alabilen herhangi bir ifade olabilir. Eğer mantıksal_durum, true olursa ifade_1 çalışacak; aksi halde, ifade_2 is çalışacaktır. ifade_1 ve ifade_2 ifadeleri, çalıştırılacak herhangi bir ifade olabilir.

+ +

Birçok mantıksal durumun kontrolünün bütün bir halde yapılabilmesi için aşağıdaki şekilde else if tanımlamalarını kullanabilirsiniz.

+ +
if (mantıksal_durum_1) {
+  ifade_1;
+} else if (mantıksal_durum_2) {
+  ifade_2;
+} else if (mantıksal_durum_n) {
+  ifade_n;
+} else {
+  ifade_son;
+}
+
+ +

Üstteki gibi çoklu mantıksal durumların olduğu ifadelerde,  yalnızca true olan ilk mantıksal durum çalıştırılır, ilişkili diğer kontrol ifadeleri çalıştırılmaz. Birçok ifadenin çalıştırılması için ifadeler, blok ifadesi ({ ... }) içerisinde gruplandırılır. Özellikle iç içe if ifadelerinin olduğu durumlar başta olmak üzere blok ifadeleri, geliştiriciler arasında yaygın olarak kullanılmaktadır:

+ +
if (mantıksal_durum) {
+  eğer_durum_true_ise_çalışacak_ifade_1;
+  eğer_durum_true_ise_çalışacak_ifade_2;
+} else {
+  eğer_durum_false_ise_çalışacak_ifade_3;
+  eğer_durum_false_ise_çalışacak_ifade_4;
+}
+
+ +
mantıksal_durum kısmında herhangi bir değişkene değer atamak yanlış bir kullanımdır, çünkü kodunuza sizden sonra bakan biri atama işlemini ilk bakışta eşitlik olarak görebilir. Örneğin aşağıdaki şekilde bir kullanım yanlıştır:
+ +
+ +
if (x = y) {
+  /* diğer ifadeler */
+}
+
+ +

Eğer mantıksal_durum kısmında gerçekten atama yapmanız gerekiyorsa, bunu yapmanın en iyi yolu atama ifadesini parantezler içerisine almaktır. Örneğin:

+ +
if ((x = y)) {
+  /* diğer ifadeler */
+}
+
+ +

Yanlışımsı (falsy) değerler

+ +

Aşağıdaki değerler JavaScript tarafından false olarak değerlendirilir ve ({{Glossary("Falsy")}} değerler olarak bilinir):

+ + + +

Mantıksal durum içerisine alınan diğer bütün değerler ve nesneler, JavaScript tarafından true olarak değerlendirilir.

+ +

{{jsxref("Boolean")}} nesnesindeki true ve false ile ilkel tipteki true ve false değerlerini karıştırmayınız. Örneğin:

+ +
var b = new Boolean(false);
+if (b) // bu ifade true olarak değerlendirilir
+
+ +

Örnek

+ +

Aşağıdaki örnekte bulunan checkData fonksiyonu, HTML dokümanındaki formda yer alan ikiKarakter isimli girdi nesnesine ait değerin, karakter sayısı 2 ise true döndürülür, değilse ekrana bir uyarı metni basılır ve false döndürülür:

+ +
function checkData() {
+  if (document.form1.ikiKarakter.value.length == 2) {
+    return true;
+  } else {
+    alert("Tam olarak iki karakter giriniz. " +
+    document.form1.ikiKarakter.value + " geçersizdir.");
+    return false;
+  }
+}
+
+ +

switch ifadesi

+ +

Bir switch ifadesine, mantıksal bir ifade verilir ve bu ifade ile eşleşen bir etiket varsa, etiketi içeren case ifadesi çalıştırılır, yoksa varsayılan ifade (default) çalıştırılır. Örnek:

+ +
switch (mantıksal_ifade) {
+  case etiket_1:
+    ifadeler_1
+    [break;]
+  case etiket_2:
+    ifadeler_2
+    [break;]
+    ...
+  default:
+    varsayılan_ifadeler
+    [break;]
+}
+
+ +

Üstteki kodu çalıştırırken JavaScript, mantıksal_ifade ile eşleşen etikete sahip case cümleciğini arar ve ilişkili ifadeleri çalıştırır. Eğer eşleşen hiçbir etiket bulunamadıysa, default cümleciğinin olup olmadığına bakar, varsa ve ilgili varsayılan ifadeleri çalıştırır. Eğer default cümleciği de yoksa, switch bloğundan çıkılır.  default cümleciğinin sırası önemli olmamakla birlikte, genel kullanımlarda hep en sonda yer almaktadır.

+ +

Her case cümleciğinde, isteğe bağlı olarak konulan break ifadesi,  eşleşen ifadenin çalıştırılıp tamamlandıktan sonra switch bloğundan çıkmayı sağlar. Eğer break ifadesi yazılmazsa, program switch ifadesi içerisindeki bir sonraki case ifadesini çalıştırarak yoluna devam eder. 

+ +

Örnek

+ +

Aşağıdaki örnekte, meyve ifadesinin değeri "Muz" ise,  program "Muz" değeri ile eşleşen case "Muz" ifadesini çalıştırır. break ile karşılaşıldığında, program switch bloğundan çıkar ve switch bloğundan sonraki kodları çalıştırır. Eğer break ifadesi olmasaydı, "Muz" ile alakasız olan, case "Kiraz" ifadesi de çalıştırılacaktı.

+ +
switch (meyve) {
+  case "Portakal":
+    console.log("Portakalların kilosu ₺1.99 lira.");
+    break;
+  case "Elma":
+    console.log("Elmaların kilosu ₺1.49 lira.");
+    break;
+  case "Muz":
+    console.log("Muzların kilosu ₺2.49 lira.");
+    break;
+  case "Kiraz":
+    console.log("Kirazların kilosu ₺2.19 lira.");
+    break;
+  case "Çilek":
+    console.log("Çileklerin kilosu ₺2.49 lira.");
+    break;
+  case "Avokado":
+    console.log("Avokadoların kilosu ₺5.99 lira.");
+    break;
+  default:
+   console.log("Maalesef elimizde hiç " + meyve + " kalmadı.");
+}
+console.log("Başka bir şey lazım mı?");
+ +

Exception (Hata) yakalama ifadeleri

+ +

throw ifadesi ile exception fırlatabilir, try...catch ifadeleri kullanarak hata yakalama işlemlerinizi yürütebilirsiniz.

+ + + +

Exception türleri

+ +

JavaScript'te neredeyse her nesne fırlatılabilir. Buna rağmen fırlatılacak türdeki nesnelerin hepsi aynı şekilde oluşturulmamışlardır. Sayı ve string değerlerinin hata olarak fırlatılması oldukça yaygın olmasına rağmen, bu amaç için belirli olarak  oluşturulan aşağıdaki exception türlerinden birinin kullanılması daha anlamlıdır:

+ + + +

throw ifadesi

+ +

Bir exception fırlatmak için throw ifadesini kullanılır. Bir exception fırlattığınız zaman, fırlatılacak ifadeyi de belirlersiniz:

+ +
throw ifade;
+
+ +

Herhangi bir türdeki ifadeyi exception olarak fırlatabilirsiniz. Aşağıdaki kodda çeşitli türlerdeki exception'lar fırlatılmaktadır:

+ +
throw "Hata2";   // String türü
+throw 42;         // Sayı türü
+throw true;       // Boolean türü
+throw { toString: function() { return "Ben bir nesneyim."; } };
+
+ +
Not: Bir exception fırlatırken ilgili exception nesnesini belirleyebilirsiniz. Daha sonra catch bloğunda hatayı yakaladığınızda ilgili exception nesnesinin özelliklerine erişebilirsiniz. Aşağıdaki ifadede, KullanıcıHatası sınıfından bir nesne oluşturulmakta, ve throw ifadesinde bu nesne fırlatılmaktadır.
+ +
// KullanıcıHatası türünde nesne oluşturuluyor
+function KullanıcıHatası(mesaj){
+  this.mesaj=mesaj;
+  this.adı="KullanıcıHatası";
+}
+
+// Oluşturulan KullanıcıHatası nesnesinin konsola yazıldığında güzel bir
+// ifade yazılması için aşağıdaki şekilde toString() fonksiyonunu override ediyoruz.
+KullanıcıHatası.prototype.toString = function () {
+  return this.adı+ ': "' + this.mesaj+ '"';
+}
+
+// KullanıcıHatası nesnesi yaratılır ve exception olarak fırlatılır
+throw new KullanıcıHatası("Yanlış bir değer girdiniz.");
+ +

try...catch ifadesi

+ +

try...catch ifadesi, çalıştırılması istenen ifadeleri bir blokta tutar. Fırlatılacak exception için bir veya daha fazla ifade belirlenerek, oluşacak bir try...catch ifadesi tarafından yakalanması sağlanır.

+ +

try...catch ifadesi, çalıştırılacak bir veya daha fazla komutun yer aldığı, ve try bloğu içerisinde hata oluştuğunda çalışacak ifadeleri içeren, 0 veya daha fazla catch ifadesinin yer aldığı bir try bloğu içerir. Bu şekilde, try içerisinde yer alan başarıyla çalışmasını istediğiniz kodlarda bir sorun oluştuğunda, catch bloğunda bu sorunun üstesinden gelecek kontrolleri yazabilirsiniz. Eğer try bloğu içerisindeki herhangi bir ifade (veya try bloğu içerisinden çağırılan fonksiyon) bir exception fırlatırsa, JavaScript anında catch bloğuna bakar. Eğer try bloğu içerisinde bir exception fırlatılmazsa, catch bloğu çalıştırılmaz ve atlanır. try ve catch bloklarından sonra, eğer varsa finally bloğu da çalıştırılır.

+ +

Aşağıdaki örnekte bir try...catch ifadesi kullanılmaktadır. Fonksiyonda, parametre olarak geçilen ay sayısı değeri baz alınarak, diziden ilgili ayın adı getirilmektedir. Eğer ay sayısı değeri 1-12 arasında değilse, "Geçersiz ay sayısı." değeri exception olarak fırlatılır. catch bloğundaki ayAdı değişkeni de "bilinmeyen" olarak atanır.

+ +
function getAyAdı(aySayisi) {
+  aySayisi= aySayisi-1; // Dizi indeksi için aySayisi 1 azaltılır (1=Oca, 12=Ara)
+  var aylar= ["Oca","Şub","Mar","Nis","May","Haz","Tem",
+                "Ağu","Eyl","Eki","Kas","Ara"];
+  if (aylar[aySayisi] != null) {
+    return aylar[aySayisi];
+  } else {
+    throw "Geçersiz ay sayısı."; // burada throw ifadesi kullanılıyor
+  }
+}
+
+try { // denenecek ifadeler
+  ayAdı = getAyAdı(aySayim); // function could throw exception
+}
+catch (e) {
+  ayAdı = "bilinmiyor";
+  hatalarımıKaydet(e); // hataların kaydedilmesi için exception nesnesi geçiliyor.
+}
+
+ +

catch bloğu

+ +

try bloğunda oluşturulan tüm exception'ların yakalanması için catch bloğunu kullanabilirsiniz.

+ +
catch (exceptionDeğişkeni) {
+  ifadeler
+}
+
+ +

catch bloğunda, throw ifadesi tarafından belirlenecek değerin tutulması için bir değişken tanımlanır; bu değişken kullanılarak, fırlatılan exception ile ilgili bilgiler elde edilmiş olur. catch bloğuna girildiğinde JavaScript, bu değişkenin içini doldurur; değişken değeri sadece catch bloğu süresince geçerli kalır; catch bloğu çalışmasını tamamladığında değişken artık mevcut değildir.

+ +

Örneğin aşağıdaki kodda, bir exception fırlatılıyor, ve fırlatıldığı anda otomatik olarak catch bloğuna iletiliyor.

+ +
try {
+  throw "hata" // bir exception oluşturur.
+}
+catch (e) {
+  // herhangi bir exception'ı yakalamak için oluşturulan ifadeler
+  hatalarımıKaydet(e) // hataların kaydedilmesi için exception nesnesi geçilir.
+}
+
+ +

finally bloğu

+ +

finally bloğu, try...catch ifadesinden sonra çalıştırılacak kod satırlarını içerir. finally bloğu, hata olsun veya olmasın çalışır. Eğer hata olmuşsa ve exception fırlatılmışsa, bu hatayı karşılayacak catch bloğu olmasa dahi finally bloğu çalışır. 

+ +

finally bloğu, hata oluştuğunda bu hataya sebep olan değişkenin kullandığı kaynakların sisteme geri verilmesi için en iyi yerdir. Bu şekilde hata tüm ayrıntılarıyla çözülmüş olur. Aşağıdaki örnekte bir dosya açılmakta, ve sonrasında dosyaya yazma işlemleri için kullanan ifadeler çalıştırılmaktadır (Sunucu taraflı yazılmış koddur. İstemci tarafında dosyaya yazma işlemleri güvenlik açısından engellenmiştir. Eğer dosya, yazmak için açılırken bir exception fırlatılırsa, kod hata vermeden önce finally bloğu çalışır ve erişilecek dosyayı kapatır.

+ +
dosyaAç();
+try {
+  dosyayaYaz(veriler); // Bu kısım hata verebilir
+} catch(e) {
+  hatayıKaydetveGöster(e); // Hata ile ilgili bilgiler kaydedilir ve kullanıcıya bir hata mesajı sunulur.
+} finally {
+  dosyayıKapat(); // Dosyayı kapatır (hata olsa da olmasa da).
+}
+
+ +

Eğer finally bloğu bir değer geri döndürürse,  bu değer, try ve catch içerisindeki return ifadelerine bakmaksızın, try-catch-finally ifadesinin tamamı için geri dönüş değeri haline gelir:

+ +
function f() {
+  try {
+    console.log(0);
+    throw "hata";
+  } catch(e) {
+    console.log(1);
+    return true; // Buradaki return ifadesi,
+                 // finally bloğu tamamlanana dek duraklatılır.
+    console.log(2); // Üstteki return ifadesinden dolayı çalıştırılmaz.
+  } finally {
+    console.log(3);
+    return false; // catch kısmındaki return ifadesinin üstüne yazar ve geçersiz hale getirir.
+    console.log(4); // return'den dolayı çalıştırılmaz.
+  }
+  // Şimdi "return false" ifadesi çalıştırılır ve fonksiyondan çıkılır.
+  console.log(5); // Çalıştırılmaz.
+}
+f(); // Konsola 0 1 3 yazar ve false değerini döndürür.
+
+ +

finally bloğunun, geri dönüş değerlerinin üstüne yazma etkisi, aynı zamanda catch bloğu içerisindeki exception'lar için de aynı şekilde çalışır:

+ +
function f() {
+  try {
+    throw "hata";
+  } catch(e) {
+    console.log('İçerideki "hata" yakalandı.');
+    throw e; // Burası finally bloğu tamamlanana dek duraklatılır.
+  } finally {
+    return false; // Önceki "throw" ifadesinin üstüne yazar ve
+                  //  throw ifadesini geçersiz hale getirir.
+  }
+  // Şimdi "return false" ifadesi çalıştırılır.
+}
+
+try {
+  f();
+} catch(e) {
+  // f() fonksiyonundaki throw ifadesi geçersiz hale geldiği için
+  //  buradaki catch bloğu çalıştırılmaz.
+  console.log('Diğer "hata" yakalandı.');
+}
+
+// Ekran çıktısı: İçerideki "hata" yakalandı.
+ +

İçiçe try...catch ifadeleri

+ +

Bir veya daha fazla iç içe try...catch ifadeleri tanımlayabilirsiniz. Eğer içteki try...catch ifadesinin catch bloğu yoksa, bir dıştaki try...catch ifadesinin catch bloğu kontrol edilir.

+ +

Error nesnelerinin etkili kullanımı

+ +

Error nesnesinin türüne bağlı olarak,  'name' ve 'message' özellikleri vasıtasıyla daha anlamlı hata mesajları tanımlayabilirsiniz. 'name' özelliği, oluşan hatayı sınıflandırır (örn, 'DOMException' veya 'Error'). 'message' ise hata nesnesinin string'e dönüştürülmesine nazaran  genellikle daha kısa bir mesaj sunulmasına olanak tanır.

+ +

Eğer kendi exception nesnelerinizi fırlatıyorsanız ve bu özellikleri kullanarak hatayı anlamlı hale getirmek istiyorsanız Error sınıfının yapıcısının getirdiği avantajlardan faydalanabilirsiniz (örneğin catch bloğunuzun, kendi exception'larınız ile sistem exception'ları arasındaki farkı ayırt edemediği gibi durumlarda). Aşağıdaki örneği inceleyelim:

+ +
function hatayaMeyilliFonksiyon() {
+  if (hataVerenFonksiyonumuz()) {
+    throw (new Error('Hata oluştu'));
+  } else {
+    sistemHatasıVerenFonksiyon();
+  }
+}
+
+try {
+  hatayaMeyilliFonksiyon();
+}
+catch (e) {
+  console.log(e.name); // 'Error' yazar
+  console.log(e.message); // 'Hata oluştu' veya bir JavaScript hata mesajı yazar
+}
+ +

Promise nesneleri

+ +

ECMAScript2015 ile birlikte JavaScript'e, asenkron ve geciktirilmiş işlemlerin akış kontrolünün sağlanması için {{jsxref("Promise")}} nesneleri gelmiştir.

+ +

Bir Promise nesnesi aşağıdaki durumlardan birinde bulunur:

+ + + +

+ +

XHR ile resim yükleme

+ +

Promise ve XMLHttpRequest kullanarak bir resmin yüklenmesi için MDN GitHub promise-test sayfasında basit bir örnek mevcuttur. Ayrıca örneği canlı olarak da görebilirsiniz. Örnekteki her aşamaya yorum satırları eklenmiştir. Bu sayede Promise ve XHR mimarisini daha yakından izleyebilirsiniz. Aşağıda Promise nesnesinin akışını gösteren örneğin belgelendirilmemiş sürümü bulunmaktadır:

+ +
function resimYükle(url) {
+  return new Promise(function(başarıSonucundaFonk, hataSonucundaFonk) {
+    var istek = new XMLHttpRequest();
+    istek.open('GET', url);
+    istek.responseType = 'blob';
+    istek.onload = function() {
+      if (istek.status === 200) {
+        başarıSonucundaFonk(istek.cevabı);
+      } else {
+        hataSonucundaFonk(Error('Resim yüklenemedi; hata kodu:'
+                     + istek.hataKodu));
+      }
+    };
+    istek.onerror = function() {
+      hataSonucundaFonk(Error('Bir bağlantı hatası oluştu.'));
+    };
+    istek.send();
+  });
+}
+ +

Daha fazla detaylı bilgi için {{jsxref("Promise")}} sayfasına bakınız.

+ +
{{PreviousNext("Web/JavaScript/Guide/Grammar_and_types", "Web/JavaScript/Guide/Loops_and_iteration")}}
diff --git a/files/tr/web/javascript/guide/fonksiyonlar/index.html b/files/tr/web/javascript/guide/fonksiyonlar/index.html deleted file mode 100644 index e688bd5dcb..0000000000 --- a/files/tr/web/javascript/guide/fonksiyonlar/index.html +++ /dev/null @@ -1,662 +0,0 @@ ---- -title: Fonksiyonlar -slug: Web/JavaScript/Guide/Fonksiyonlar -tags: - - Başlangıç seviyesi - - Fonksiyonlar - - Rehber -translation_of: Web/JavaScript/Guide/Functions ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Loops_and_iteration", "Web/JavaScript/Guide/Expressions_and_Operators")}}
- -

Foksiyonlar, JavaScript'in en temel yapıtaşlarından biridir. Her bir fonksiyon, bir JavaScript işlemidir—herhangi bir görevi yerine getiren  veya değer hesaplayan bir ifade kümesini içerirler. Bir fonksiyonu kullanmak için, fonksiyonu çağıracağınız kısmın faaliyet gösterdiği alanda fonksiyonu tanımlıyor olmanız gerekmektedir.

- -

Daha fazla bilgi için JavaScript fonksiyonları ile ilgili buradaki detaylı kaynağı inceleyebilirsiniz.

- -

Fonksiyonların tanımlanması

- -

Fonksiyon tanımlamaları

- -

Bir fonksiyon tanımı (fonksiyon betimlemesi, veya fonksiyon ifadesi de denir)  function anahtar kelimesinden sonra aşağıdaki kısımları içerir:

- - - -

Örneğin aşağıdaki kodda karesiniAl isimli basit bir fonksiyon tanımlanmıştır:

- -
function karesiniAl(sayı) {
-  return sayı * sayı;
-}
-
- -

karesiniAl fonksiyonu, sayı isminde tek bir parametre içerir. Tek bir ifade içeren fonksiyonda, sayı parametresinin kendisi ile çarpılıp geri döndürülmesi işlemi yapılmıştır. return ifadesi, fonksiyon tarafından döndürülen değeri belirler.

- -
return sayı * sayı;
-
- -

Sayı türünde olduğu gibi ilkel parametreler fonksiyonlara değer ile geçilirler; ilgili değer, fonksiyona parametre olarak geçildiğinde parametre değerinin fonksiyonda ayrı bir kopyası alınır, eğer fonksiyon içerisinde parametre değerinde değişik yapılırsa, bu değişiklik sadece kopyalanan değer üzerinde gerçekleşmiştir, fonksiyona geçilen asıl değer değişmez.

- -

Eğer bir nesneyi ({{jsxref("Array")}} veya bir kullanıcı tanımlı nesne gibi ilkel olmayan değer) fonksiyona parametre olarak geçerseniz, nesne fonksiyon içerisinde kopyalanmadığı için nesne üzerinde yapılan değişiklikler fonksiyon dışında da korunur. Aşağıdaki örneği inceleyelim:

- -
function arabamıDeğiştir(araba) {
-  araba.markası = "Toyota";
-}
-
-var arabam = {markası: "Honda", modeli: "Accord", yılı: 1998};
-var x, y;
-
-x = arabam.markası ; // "Honda" değerini getirir
-
-arabamıDeğiştir(arabam);
-y = arabam.markası; // "Toyota" değeri döndürülür
-                    // (markası özelliği fonksiyon tarafından değiştirilmiştir)
-
- -

Fonksiyon ifadeleri

- -

Yukarıdaki fonksiyon tanımlaması sözdizimsel olarak bir ifade olmasına rağmen, fonksiyonlar ayrıca bir fonksiyon ifadesi ile de oluşturulabilirler. Böyle bir fonksiyon anonim olabilir; bir isme sahip olmak zorunda değildir. Örnek olarak, matematikteki kare alma fonksiyonu aşağıdaki şekilde tanımlanabilir:

- -
var karesiniAl = function(sayı) { return sayı * sayı };
-var x = karesiniAl(4) // x'in değeri 16 olur.
- -

Fonksiyon ifadesi ile belirtilen fonksiyon adı, fonksiyonun içerisinde kendisini çağıracak şekilde kullanılabilir:

- -
var faktoriyel = function fa(n) { return n < 2 ? 1 : n * fa(n-1) };
-
-console.log(faktoriyel(3));
-
- -

Fonksiyon ifadeleri, bir fonksiyon diğer fonksiyona parametre olarak geçilirken oldukça elverişlidir. Aşağıdaki örnekte map fonksiyonu tanımlanmış ve ilk parametresinde başka bir fonksiyonu parametre olarak almıştır:

- -
function map(f,d) {
-  var sonuç = [], // Yeni bir dizi
-      i;
-  for (i = 0; i != d.length; i++)
-    sonuç[i] = f(d[i]);
-  return sonuç;
-}
-
- -

Aşağıdaki kodda kullanımı mevcuttur:

- -
var çarpım = function(x) {return x * x * x}; // Fonksiyon ifadesi.
-map(çarpım, [0, 1, 2, 5, 10]);
-
- -

[0, 1, 8, 125, 1000] dizisini döndürür.

- -

JavaScript'te bir fonksiyon, herhangi bir duruma bağlı olarak oluşturulabilir.Örneğin aşağıdaki fonksiyonda benimFonk fonksiyonu, sayı değeri sadece 0'a eşit olursa tanımlanır:

- -
var benimFonk;
-if (sayı === 0){
-  benimFonk = function(araba) {
-    araba.marka = "Toyota"
-  }
-}
- -

Burada tanımlanan fonksiyonlara ek olarak {{jsxref("Function")}} yapıcısını kullanarak da çalışma zamanında fonksiyon oluşmasını sağlanabilir. Örneğin {{jsxref("eval", "eval()")}} ifadesi gibi.

- -

Bir nesnenin özelliği olan fonksiyona metot adı verilir. Nesneler ve metotlar hakkında daha fazla bilgi için bkz: Nesneler ile çalışma.

- -

Fonksiyonları çağırma

- -

Bir fonksiyonu tanımlamakla o fonksiyon çalışmaz. Fonksiyonu tanımlamak kısaca, o fonksiyona bir isim vermek ve o fonkisyon çağırıldığında bizim için hangi eylemleri yapması gerektiğini belirtmektir. Fonksiyonu çağırmak, bu belirlenmiş eylemleri bizim o fonksiyona verdiğimiz parametrelerin de kullanılmasıyla gerçekleştirir.  Örneğin,  karesiniAl diye bir fonksiyon tanımladığınızda, o fonksiyonu aşağıdaki gibi çağırabilirsiniz:

- -
karesiniAl(5);
-
- -

Bu ifade, fonksiyona parametre olarak 5 sayısını yollayarak çağırır. Fonksiyon, tanımlanırken belirttiğimiz eylemleri yapar ve bize 25 değerini döndürür.

- -

Fonksiyonlar çağrıldıklarında bir alanda olmalıdılar, fakat fonksiyon bildirimi kaldırılabilir, örnekteki gibi:

- -
console.log(square(5));
-/* ... */
-function square(n) { return n * n }
-
- -

Bir fonksiyonun alanı, bildirilen işlevdir, veya tüm program üst seviyede bildirilmişse.

- -
-

Not:  Bu, yalnızca yukarıdaki sözdizimini (i.e. function benimFonk(){}) işlevini kullanarak işlevi tanımlarken çalışır. Aşağıdaki kod çalışmayacak. Yani, işlev kaldırma sadece işlev bildirimi ile çalışır ve işlev ifadesiyle çalışamaz.

-
- -
console.log(square); // square is hoisted with an initial value undefined.
-console.log(square(5)); // TypeError: square is not a function
-var square = function (n) {
-  return n * n;
-}
-
- -

Bir fonksiyonun argümanları karakter dizileri ve sayılarla sınırlı değildir. Tüm nesneleri bir fonksiyona aktarabilirsiniz. show_props() fonksiyonu (Working with objects bölümünde tanımlanmıştır.) nesneyi argüman olarak alan bir fonksiyon örneğidir.

- -

Bir fonksiyon kendini çağırabilir. Örneğin, burada faktöriyelleri yinelemeli olarak hesaplayan bir fonksiyon var.

- -
function factorial(n){
-  if ((n === 0) || (n === 1))
-    return 1;
-  else
-    return (n * factorial(n - 1));
-}
-
- -

Daha sonra bir ile beş arasındaki faktöriyelleri şu şekilde hesaplayabilirsiniz:

- -
var a, b, c, d, e;
-a = factorial(1); // a gets the value 1
-b = factorial(2); // b gets the value 2
-c = factorial(3); // c gets the value 6
-d = factorial(4); // d gets the value 24
-e = factorial(5); // e gets the value 120
-
- -

Fonksiyonları  çağırmanın başka yolları da var. Bir fonksiyonun dinamik olarak çağrılması gerektiği veya bir fonksiyonun argümanlarının sayısının değişebileceği veya fonksiyon çağrısının içeriğinin çalışma zamanında belirlenen belirli bir nesneye ayarlanması gerektiği durumlar vardır. Fonksiyonların kendileri nesneler olduğu ve bu nesnelerin sırasıyla yöntemleri olduğu anlaşılıyor (bkz. {{Jsxref ("Function")}} nesnesi). Bunlardan biri, {{jsxref ("Function.apply", "application ()")}} yöntemi, bu amaca ulaşmak için kullanılabilir.

- -

Fonksiyon Kapsamı

- -

Bir fonksiyon içinde tanımlanmış değişkenlere, fonksiyonun dışındaki herhangi bir yerden erişilemez, çünkü değişken sadece fonksiyon kapsamında tanımlanır. Bununla birlikte, bir fonksiyon tanımlandığı kapsamda tanımlanan tüm değişkenlere ve fonksiyonlara erişebilir. Başka bir deyişle, global kapsamda tanımlanan bir fonksiyon, global kapsamda tanımlanan tüm değişkenlere erişebilir. Başka bir fonksiyonun içinde tanımlanmış bir fonksiyon, ana fonksiyonunda tanımlanan tüm değişkenlere ve ana fonksiyonun erişebildiği herhangi bir değişkene de erişebilir.

- -
// The following variables are defined in the global scope
-var num1 = 20,
-    num2 = 3,
-    name = "Chamahk";
-
-// This function is defined in the global scope
-function multiply() {
-  return num1 * num2;
-}
-
-multiply(); // Returns 60
-
-// A nested function example
-function getScore () {
-  var num1 = 2,
-      num2 = 3;
-
-  function add() {
-    return name + " scored " + (num1 + num2);
-  }
-
-  return add();
-}
-
-getScore(); // Returns "Chamahk scored 5"
- -

Kapsam ve fonksiyon yığını

- -

Yineleme

- -

Bir fonksiyon kendisine başvurabilir ve kendisini arayabilir. Bir işlevin kendisine başvurması için üç yol vardır:

- -

 

- -
    -
  1. fonksiyonun adı
  2. -
  3. arguments.callee
  4. -
  5. -

    fonksiyona başvuran bir kapsam içi değişken  

    -
  6. -
- -
-
-
-

Örneğin, aşağıdaki işlev tanımını göz önünde bulundurun:

-
-
-
- -

 

- -
var foo = function bar() {
-   // statements go here
-};
-
- -

Fonksiyon gövdesinde aşağıdakilerden hepsi eşdeğerdir.

- -
    -
  1. bar()
  2. -
  3. arguments.callee()
  4. -
  5. foo()
  6. -
- -

Kendisini çağıran fonksiyona özyinelemeli fonksiyon denir. Bazı açılardan, özyineleme bir döngüye benzer. Her ikisi de aynı kodu birkaç kez uygular ve her ikisi de bir koşul gerektirir (bu, sonsuz bir döngüden kaçınmak veya daha doğrusu bu durumda sonsuz özyinelemeden kaçınmak için). Örneğin, aşağıdaki döngü:

- -
var x = 0;
-while (x < 10) { // "x < 10" is the loop condition
-   // do stuff
-   x++;
-}
-
- -

özyinelemeli bir fonksiyona ve bu fonksiyonun çağrısına dönüştürülebilir:

- -
function loop(x) {
-  if (x >= 10) // "x >= 10" is the exit condition (equivalent to "!(x < 10)")
-    return;
-  // do stuff
-  loop(x + 1); // the recursive call
-}
-loop(0);
-
- -

Ancak, bazı algoritmalar basit yinelemeli döngüler olamaz. Örneğin, bir ağaç yapısının tüm düğümlerinin (örneğin DOM) alınması özyineleme kullanılarak daha kolay yapılır:

- -
function walkTree(node) {
-  if (node == null) //
-    return;
-  // do something with node
-  for (var i = 0; i < node.childNodes.length; i++) {
-    walkTree(node.childNodes[i]);
-  }
-}
-
- -

Fonksiyon döngüsü ile karşılaştırıldığında, her özyinelemeli çağrının kendisi burada birçok özyinelemeli çağrı yapar.

- -

Herhangi bir özyinelemeli algoritmayı özyinelemeli olmayan bir algoritmaya dönüştürmek mümkündür, ancak çoğu zaman mantık çok daha karmaşıktır ve bunu yapmak bir yığının kullanılmasını gerektirir. Aslında, özyinelemenin kendisi bir yığın kullanır: Fonksiyon yığını.

- -

Yığın benzeri davranış aşağıdaki örnekte görülebilir:

- -
function foo(i) {
-  if (i < 0)
-    return;
-  console.log('begin:' + i);
-  foo(i - 1);
-  console.log('end:' + i);
-}
-foo(3);
-
-// Output:
-
-// begin:3
-// begin:2
-// begin:1
-// begin:0
-// end:0
-// end:1
-// end:2
-// end:3
- -

Nested functions and closures

- -

You can nest a function within a function. The nested (inner) function is private to its containing (outer) function. It also forms a closure. A closure is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).

- -

Since a nested function is a closure, this means that a nested function can "inherit" the arguments and variables of its containing function. In other words, the inner function contains the scope of the outer function.

- -

To summarize:

- - - - - -

The following example shows nested functions:

- -
function addSquares(a,b) {
-  function square(x) {
-    return x * x;
-  }
-  return square(a) + square(b);
-}
-a = addSquares(2,3); // returns 13
-b = addSquares(3,4); // returns 25
-c = addSquares(4,5); // returns 41
-
- -

Since the inner function forms a closure, you can call the outer function and specify arguments for both the outer and inner function:

- -
function outside(x) {
-  function inside(y) {
-    return x + y;
-  }
-  return inside;
-}
-fn_inside = outside(3); // Think of it like: give me a function that adds 3 to whatever you give it
-result = fn_inside(5); // returns 8
-
-result1 = outside(3)(5); // returns 8
-
- -

Preservation of variables

- -

Notice how x is preserved when inside is returned. A closure must preserve the arguments and variables in all scopes it references. Since each call provides potentially different arguments, a new closure is created for each call to outside. The memory can be freed only when the returned inside is no longer accessible.

- -

This is not different from storing references in other objects, but is often less obvious because one does not set the references directly and cannot inspect them.

- -

Multiply-nested functions

- -

Functions can be multiply-nested, i.e. a function (A) containing a function (B) containing a function (C). Both functions B and C form closures here, so B can access A and C can access B. In addition, since C can access B which can access A, C can also access A. Thus, the closures can contain multiple scopes; they recursively contain the scope of the functions containing it. This is called scope chaining. (Why it is called "chaining" will be explained later.)

- -

Consider the following example:

- -
function A(x) {
-  function B(y) {
-    function C(z) {
-      console.log(x + y + z);
-    }
-    C(3);
-  }
-  B(2);
-}
-A(1); // logs 6 (1 + 2 + 3)
-
- -

In this example, C accesses B's y and A's x. This can be done because:

- -
    -
  1. B forms a closure including A, i.e. B can access A's arguments and variables.
  2. -
  3. C forms a closure including B.
  4. -
  5. Because B's closure includes A, C's closure includes A, C can access both B and A's arguments and variables. In other words, C chains the scopes of B and A in that order.
  6. -
- -

The reverse, however, is not true. A cannot access C, because A cannot access any argument or variable of B, which C is a variable of. Thus, C remains private to only B.

- -

Name conflicts

- -

When two arguments or variables in the scopes of a closure have the same name, there is a name conflict. More inner scopes take precedence, so the inner-most scope takes the highest precedence, while the outer-most scope takes the lowest. This is the scope chain. The first on the chain is the inner-most scope, and the last is the outer-most scope. Consider the following:

- -
function outside() {
-  var x = 10;
-  function inside(x) {
-    return x;
-  }
-  return inside;
-}
-result = outside()(20); // returns 20 instead of 10
-
- -

The name conflict happens at the statement return x and is between inside's parameter x and outside's variable x. The scope chain here is {inside, outside, global object}. Therefore inside's x takes precedences over outside's x, and 20 (inside's x) is returned instead of 10 (outside's x).

- -

Closures

- -

Closures are one of the most powerful features of JavaScript. JavaScript allows for the nesting of functions and grants the inner function full access to all the variables and functions defined inside the outer function (and all other variables and functions that the outer function has access to). However, the outer function does not have access to the variables and functions defined inside the inner function. This provides a sort of security for the variables of the inner function. Also, since the inner function has access to the scope of the outer function, the variables and functions defined in the outer function will live longer than the outer function itself, if the inner function manages to survive beyond the life of the outer function. A closure is created when the inner function is somehow made available to any scope outside the outer function.

- -
var pet = function(name) {   // The outer function defines a variable called "name"
-  var getName = function() {
-    return name;             // The inner function has access to the "name" variable of the outer function
-  }
-  return getName;            // Return the inner function, thereby exposing it to outer scopes
-}
-myPet = pet("Vivie");
-
-myPet();                     // Returns "Vivie"
-
- -

It can be much more complex than the code above. An object containing methods for manipulating the inner variables of the outer function can be returned.

- -
var createPet = function(name) {
-  var sex;
-
-  return {
-    setName: function(newName) {
-      name = newName;
-    },
-
-    getName: function() {
-      return name;
-    },
-
-    getSex: function() {
-      return sex;
-    },
-
-    setSex: function(newSex) {
-      if(typeof newSex === "string" && (newSex.toLowerCase() === "male" || newSex.toLowerCase() === "female")) {
-        sex = newSex;
-      }
-    }
-  }
-}
-
-var pet = createPet("Vivie");
-pet.getName();                  // Vivie
-
-pet.setName("Oliver");
-pet.setSex("male");
-pet.getSex();                   // male
-pet.getName();                  // Oliver
-
- -

In the code above, the name variable of the outer function is accessible to the inner functions, and there is no other way to access the inner variables except through the inner functions. The inner variables of the inner functions act as safe stores for the outer arguments and variables. They hold "persistent", yet secure, data for the inner functions to work with. The functions do not even have to be assigned to a variable, or have a name.

- -
var getCode = (function(){
-  var secureCode = "0]Eal(eh&2";    // A code we do not want outsiders to be able to modify...
-
-  return function () {
-    return secureCode;
-  };
-})();
-
-getCode();    // Returns the secureCode
-
- -

There are, however, a number of pitfalls to watch out for when using closures. If an enclosed function defines a variable with the same name as the name of a variable in the outer scope, there is no way to refer to the variable in the outer scope again.

- -
var createPet = function(name) {  // Outer function defines a variable called "name"
-  return {
-    setName: function(name) {    // Enclosed function also defines a variable called "name"
-      name = name;               // ??? How do we access the "name" defined by the outer function ???
-    }
-  }
-}
-
- -

The magical this variable is very tricky in closures. They have to be used carefully, as what this refers to depends completely on where the function was called, rather than where it was defined.

- -

Using the arguments object

- -

The arguments of a function are maintained in an array-like object. Within a function, you can address the arguments passed to it as follows:

- -
arguments[i]
-
- -

where i is the ordinal number of the argument, starting at zero. So, the first argument passed to a function would be arguments[0]. The total number of arguments is indicated by arguments.length.

- -

Using the arguments object, you can call a function with more arguments than it is formally declared to accept. This is often useful if you don't know in advance how many arguments will be passed to the function. You can use arguments.length to determine the number of arguments actually passed to the function, and then access each argument using the arguments object.

- -

For example, consider a function that concatenates several strings. The only formal argument for the function is a string that specifies the characters that separate the items to concatenate. The function is defined as follows:

- -
function myConcat(separator) {
-   var result = ""; // initialize list
-   var i;
-   // iterate through arguments
-   for (i = 1; i < arguments.length; i++) {
-      result += arguments[i] + separator;
-   }
-   return result;
-}
-
- -

You can pass any number of arguments to this function, and it concatenates each argument into a string "list":

- -
// returns "red, orange, blue, "
-myConcat(", ", "red", "orange", "blue");
-
-// returns "elephant; giraffe; lion; cheetah; "
-myConcat("; ", "elephant", "giraffe", "lion", "cheetah");
-
-// returns "sage. basil. oregano. pepper. parsley. "
-myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley");
-
- -
-

Note: The arguments variable is "array-like", but not an array. It is array-like in that is has a numbered index and a length property. However, it does not possess all of the array-manipulation methods.

-
- -

See the {{jsxref("Function")}} object in the JavaScript reference for more information.

- -

Function parameters

- -

Starting with ECMAScript 6, there are two new kinds of parameters: default parameters and rest parameters.

- -

Default parameters

- -

In JavaScript, parameters of functions default to undefined. However, in some situations it might be useful to set a different default value. This is where default parameters can help.

- -

In the past, the general strategy for setting defaults was to test parameter values in the body of the function and assign a value if they are undefined. If in the following example, no value is provided for b in the call, its value would be undefined  when evaluating a*b and the call to multiply would have returned NaN. However, this is caught with the second line in this example:

- -
function multiply(a, b) {
-  b = typeof b !== 'undefined' ?  b : 1;
-
-  return a*b;
-}
-
-multiply(5); // 5
-
- -

With default parameters, the check in the function body is no longer necessary. Now, you can simply put 1 as the default value for b in the function head:

- -
function multiply(a, b = 1) {
-  return a*b;
-}
-
-multiply(5); // 5
- -

Fore more details, see default parameters in the reference.

- -

Rest parameters

- -

The rest parameter syntax allows us to represent an indefinite number of arguments as an array. In the example, we use the rest parameters to collect arguments from the second one to the end. We then multiply them by the first one. This example is using an arrow function, which is introduced in the next section.

- -
function multiply(multiplier, ...theArgs) {
-  return theArgs.map(x => multiplier * x);
-}
-
-var arr = multiply(2, 1, 2, 3);
-console.log(arr); // [2, 4, 6]
- -

Arrow functions

- -

An arrow function expression (also known as fat arrow function) has a shorter syntax compared to function expressions and lexically binds the this value. Arrow functions are always anonymous. See also this hacks.mozilla.org blog post: "ES6 In Depth: Arrow functions".

- -

Two factors influenced the introduction of arrow functions: shorter functions and lexical this.

- -

Shorter functions

- -

In some functional patterns, shorter functions are welcome. Compare:

- -
var a = [
-  "Hydrogen",
-  "Helium",
-  "Lithium",
-  "Beryllium"
-];
-
-var a2 = a.map(function(s){ return s.length });
-
-console.log(a2); // logs [ 8, 6, 7, 9 ]
-
-var a3 = a.map( s => s.length );
-
-console.log(a3); // logs [ 8, 6, 7, 9 ]
-
- -

Lexical this

- -

Until arrow functions, every new function defined its own this value (a new object in case of a constructor, undefined in strict mode function calls, the context object if the function is called as an "object method", etc.). This proved to be annoying with an object-oriented style of programming.

- -
function Person() {
-  // The Person() constructor defines `this` as itself.
-  this.age = 0;
-
-  setInterval(function growUp() {
-    // In nonstrict mode, the growUp() function defines `this`
-    // as the global object, which is different from the `this`
-    // defined by the Person() constructor.
-    this.age++;
-  }, 1000);
-}
-
-var p = new Person();
- -

In ECMAScript 3/5, this issue was fixed by assigning the value in this to a variable that could be closed over.

- -
function Person() {
-  var self = this; // Some choose `that` instead of `self`.
-                   // Choose one and be consistent.
-  self.age = 0;
-
-  setInterval(function growUp() {
-    // The callback refers to the `self` variable of which
-    // the value is the expected object.
-    self.age++;
-  }, 1000);
-}
- -

Alternatively, a bound function could be created so that the proper this value would be passed to the growUp() function.

- -

Arrow functions capture the this value of the enclosing context, so the following code works as expected.

- -
function Person(){
-  this.age = 0;
-
-  setInterval(() => {
-    this.age++; // |this| properly refers to the person object
-  }, 1000);
-}
-
-var p = new Person();
- -

Predefined functions

- -

JavaScript has several top-level, built-in functions:

- -
-
{{jsxref("Global_Objects/eval", "eval()")}}
-
-

The eval() method evaluates JavaScript code represented as a string.

-
-
{{jsxref("Global_Objects/uneval", "uneval()")}} {{non-standard_inline}}
-
-

The uneval() method creates a string representation of the source code of an {{jsxref("Object")}}.

-
-
{{jsxref("Global_Objects/isFinite", "isFinite()")}}
-
-

The global isFinite() function determines whether the passed value is a finite number. If needed, the parameter is first converted to a number.

-
-
{{jsxref("Global_Objects/isNaN", "isNaN()")}}
-
-

The isNaN() function determines whether a value is {{jsxref("Global_Objects/NaN", "NaN")}} or not. Note: coercion inside the isNaN function has interesting rules; you may alternatively want to use {{jsxref("Number.isNaN()")}}, as defined in ECMAScript 6, or you can use typeof to determine if the value is Not-A-Number.

-
-
{{jsxref("Global_Objects/parseFloat", "parseFloat()")}}
-
-

The parseFloat() function parses a string argument and returns a floating point number.

-
-
{{jsxref("Global_Objects/parseInt", "parseInt()")}}
-
-

The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).

-
-
{{jsxref("Global_Objects/decodeURI", "decodeURI()")}}
-
-

The decodeURI() function decodes a Uniform Resource Identifier (URI) previously created by {{jsxref("Global_Objects/encodeURI", "encodeURI")}} or by a similar routine.

-
-
{{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent()")}}
-
-

The decodeURIComponent() method decodes a Uniform Resource Identifier (URI) component previously created by {{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent")}} or by a similar routine.

-
-
{{jsxref("Global_Objects/encodeURI", "encodeURI()")}}
-
-

The encodeURI() method encodes a Uniform Resource Identifier (URI) by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).

-
-
{{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent()")}}
-
-

The encodeURIComponent() method encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).

-
-
{{jsxref("Global_Objects/escape", "escape()")}} {{deprecated_inline}}
-
-

The deprecated escape() method computes a new string in which certain characters have been replaced by a hexadecimal escape sequence. Use {{jsxref("Global_Objects/encodeURI", "encodeURI")}} or {{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent")}} instead.

-
-
{{jsxref("Global_Objects/unescape", "unescape()")}} {{deprecated_inline}}
-
-

The deprecated unescape() method computes a new string in which hexadecimal escape sequences are replaced with the character that it represents. The escape sequences might be introduced by a function like {{jsxref("Global_Objects/escape", "escape")}}. Because unescape() is deprecated, use {{jsxref("Global_Objects/decodeURI", "decodeURI()")}} or {{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent")}} instead.

-
-
- -

{{PreviousNext("Web/JavaScript/Guide/Loops_and_iteration", "Web/JavaScript/Guide/Expressions_and_Operators")}}

diff --git a/files/tr/web/javascript/guide/functions/index.html b/files/tr/web/javascript/guide/functions/index.html new file mode 100644 index 0000000000..e688bd5dcb --- /dev/null +++ b/files/tr/web/javascript/guide/functions/index.html @@ -0,0 +1,662 @@ +--- +title: Fonksiyonlar +slug: Web/JavaScript/Guide/Fonksiyonlar +tags: + - Başlangıç seviyesi + - Fonksiyonlar + - Rehber +translation_of: Web/JavaScript/Guide/Functions +--- +
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Loops_and_iteration", "Web/JavaScript/Guide/Expressions_and_Operators")}}
+ +

Foksiyonlar, JavaScript'in en temel yapıtaşlarından biridir. Her bir fonksiyon, bir JavaScript işlemidir—herhangi bir görevi yerine getiren  veya değer hesaplayan bir ifade kümesini içerirler. Bir fonksiyonu kullanmak için, fonksiyonu çağıracağınız kısmın faaliyet gösterdiği alanda fonksiyonu tanımlıyor olmanız gerekmektedir.

+ +

Daha fazla bilgi için JavaScript fonksiyonları ile ilgili buradaki detaylı kaynağı inceleyebilirsiniz.

+ +

Fonksiyonların tanımlanması

+ +

Fonksiyon tanımlamaları

+ +

Bir fonksiyon tanımı (fonksiyon betimlemesi, veya fonksiyon ifadesi de denir)  function anahtar kelimesinden sonra aşağıdaki kısımları içerir:

+ + + +

Örneğin aşağıdaki kodda karesiniAl isimli basit bir fonksiyon tanımlanmıştır:

+ +
function karesiniAl(sayı) {
+  return sayı * sayı;
+}
+
+ +

karesiniAl fonksiyonu, sayı isminde tek bir parametre içerir. Tek bir ifade içeren fonksiyonda, sayı parametresinin kendisi ile çarpılıp geri döndürülmesi işlemi yapılmıştır. return ifadesi, fonksiyon tarafından döndürülen değeri belirler.

+ +
return sayı * sayı;
+
+ +

Sayı türünde olduğu gibi ilkel parametreler fonksiyonlara değer ile geçilirler; ilgili değer, fonksiyona parametre olarak geçildiğinde parametre değerinin fonksiyonda ayrı bir kopyası alınır, eğer fonksiyon içerisinde parametre değerinde değişik yapılırsa, bu değişiklik sadece kopyalanan değer üzerinde gerçekleşmiştir, fonksiyona geçilen asıl değer değişmez.

+ +

Eğer bir nesneyi ({{jsxref("Array")}} veya bir kullanıcı tanımlı nesne gibi ilkel olmayan değer) fonksiyona parametre olarak geçerseniz, nesne fonksiyon içerisinde kopyalanmadığı için nesne üzerinde yapılan değişiklikler fonksiyon dışında da korunur. Aşağıdaki örneği inceleyelim:

+ +
function arabamıDeğiştir(araba) {
+  araba.markası = "Toyota";
+}
+
+var arabam = {markası: "Honda", modeli: "Accord", yılı: 1998};
+var x, y;
+
+x = arabam.markası ; // "Honda" değerini getirir
+
+arabamıDeğiştir(arabam);
+y = arabam.markası; // "Toyota" değeri döndürülür
+                    // (markası özelliği fonksiyon tarafından değiştirilmiştir)
+
+ +

Fonksiyon ifadeleri

+ +

Yukarıdaki fonksiyon tanımlaması sözdizimsel olarak bir ifade olmasına rağmen, fonksiyonlar ayrıca bir fonksiyon ifadesi ile de oluşturulabilirler. Böyle bir fonksiyon anonim olabilir; bir isme sahip olmak zorunda değildir. Örnek olarak, matematikteki kare alma fonksiyonu aşağıdaki şekilde tanımlanabilir:

+ +
var karesiniAl = function(sayı) { return sayı * sayı };
+var x = karesiniAl(4) // x'in değeri 16 olur.
+ +

Fonksiyon ifadesi ile belirtilen fonksiyon adı, fonksiyonun içerisinde kendisini çağıracak şekilde kullanılabilir:

+ +
var faktoriyel = function fa(n) { return n < 2 ? 1 : n * fa(n-1) };
+
+console.log(faktoriyel(3));
+
+ +

Fonksiyon ifadeleri, bir fonksiyon diğer fonksiyona parametre olarak geçilirken oldukça elverişlidir. Aşağıdaki örnekte map fonksiyonu tanımlanmış ve ilk parametresinde başka bir fonksiyonu parametre olarak almıştır:

+ +
function map(f,d) {
+  var sonuç = [], // Yeni bir dizi
+      i;
+  for (i = 0; i != d.length; i++)
+    sonuç[i] = f(d[i]);
+  return sonuç;
+}
+
+ +

Aşağıdaki kodda kullanımı mevcuttur:

+ +
var çarpım = function(x) {return x * x * x}; // Fonksiyon ifadesi.
+map(çarpım, [0, 1, 2, 5, 10]);
+
+ +

[0, 1, 8, 125, 1000] dizisini döndürür.

+ +

JavaScript'te bir fonksiyon, herhangi bir duruma bağlı olarak oluşturulabilir.Örneğin aşağıdaki fonksiyonda benimFonk fonksiyonu, sayı değeri sadece 0'a eşit olursa tanımlanır:

+ +
var benimFonk;
+if (sayı === 0){
+  benimFonk = function(araba) {
+    araba.marka = "Toyota"
+  }
+}
+ +

Burada tanımlanan fonksiyonlara ek olarak {{jsxref("Function")}} yapıcısını kullanarak da çalışma zamanında fonksiyon oluşmasını sağlanabilir. Örneğin {{jsxref("eval", "eval()")}} ifadesi gibi.

+ +

Bir nesnenin özelliği olan fonksiyona metot adı verilir. Nesneler ve metotlar hakkında daha fazla bilgi için bkz: Nesneler ile çalışma.

+ +

Fonksiyonları çağırma

+ +

Bir fonksiyonu tanımlamakla o fonksiyon çalışmaz. Fonksiyonu tanımlamak kısaca, o fonksiyona bir isim vermek ve o fonkisyon çağırıldığında bizim için hangi eylemleri yapması gerektiğini belirtmektir. Fonksiyonu çağırmak, bu belirlenmiş eylemleri bizim o fonksiyona verdiğimiz parametrelerin de kullanılmasıyla gerçekleştirir.  Örneğin,  karesiniAl diye bir fonksiyon tanımladığınızda, o fonksiyonu aşağıdaki gibi çağırabilirsiniz:

+ +
karesiniAl(5);
+
+ +

Bu ifade, fonksiyona parametre olarak 5 sayısını yollayarak çağırır. Fonksiyon, tanımlanırken belirttiğimiz eylemleri yapar ve bize 25 değerini döndürür.

+ +

Fonksiyonlar çağrıldıklarında bir alanda olmalıdılar, fakat fonksiyon bildirimi kaldırılabilir, örnekteki gibi:

+ +
console.log(square(5));
+/* ... */
+function square(n) { return n * n }
+
+ +

Bir fonksiyonun alanı, bildirilen işlevdir, veya tüm program üst seviyede bildirilmişse.

+ +
+

Not:  Bu, yalnızca yukarıdaki sözdizimini (i.e. function benimFonk(){}) işlevini kullanarak işlevi tanımlarken çalışır. Aşağıdaki kod çalışmayacak. Yani, işlev kaldırma sadece işlev bildirimi ile çalışır ve işlev ifadesiyle çalışamaz.

+
+ +
console.log(square); // square is hoisted with an initial value undefined.
+console.log(square(5)); // TypeError: square is not a function
+var square = function (n) {
+  return n * n;
+}
+
+ +

Bir fonksiyonun argümanları karakter dizileri ve sayılarla sınırlı değildir. Tüm nesneleri bir fonksiyona aktarabilirsiniz. show_props() fonksiyonu (Working with objects bölümünde tanımlanmıştır.) nesneyi argüman olarak alan bir fonksiyon örneğidir.

+ +

Bir fonksiyon kendini çağırabilir. Örneğin, burada faktöriyelleri yinelemeli olarak hesaplayan bir fonksiyon var.

+ +
function factorial(n){
+  if ((n === 0) || (n === 1))
+    return 1;
+  else
+    return (n * factorial(n - 1));
+}
+
+ +

Daha sonra bir ile beş arasındaki faktöriyelleri şu şekilde hesaplayabilirsiniz:

+ +
var a, b, c, d, e;
+a = factorial(1); // a gets the value 1
+b = factorial(2); // b gets the value 2
+c = factorial(3); // c gets the value 6
+d = factorial(4); // d gets the value 24
+e = factorial(5); // e gets the value 120
+
+ +

Fonksiyonları  çağırmanın başka yolları da var. Bir fonksiyonun dinamik olarak çağrılması gerektiği veya bir fonksiyonun argümanlarının sayısının değişebileceği veya fonksiyon çağrısının içeriğinin çalışma zamanında belirlenen belirli bir nesneye ayarlanması gerektiği durumlar vardır. Fonksiyonların kendileri nesneler olduğu ve bu nesnelerin sırasıyla yöntemleri olduğu anlaşılıyor (bkz. {{Jsxref ("Function")}} nesnesi). Bunlardan biri, {{jsxref ("Function.apply", "application ()")}} yöntemi, bu amaca ulaşmak için kullanılabilir.

+ +

Fonksiyon Kapsamı

+ +

Bir fonksiyon içinde tanımlanmış değişkenlere, fonksiyonun dışındaki herhangi bir yerden erişilemez, çünkü değişken sadece fonksiyon kapsamında tanımlanır. Bununla birlikte, bir fonksiyon tanımlandığı kapsamda tanımlanan tüm değişkenlere ve fonksiyonlara erişebilir. Başka bir deyişle, global kapsamda tanımlanan bir fonksiyon, global kapsamda tanımlanan tüm değişkenlere erişebilir. Başka bir fonksiyonun içinde tanımlanmış bir fonksiyon, ana fonksiyonunda tanımlanan tüm değişkenlere ve ana fonksiyonun erişebildiği herhangi bir değişkene de erişebilir.

+ +
// The following variables are defined in the global scope
+var num1 = 20,
+    num2 = 3,
+    name = "Chamahk";
+
+// This function is defined in the global scope
+function multiply() {
+  return num1 * num2;
+}
+
+multiply(); // Returns 60
+
+// A nested function example
+function getScore () {
+  var num1 = 2,
+      num2 = 3;
+
+  function add() {
+    return name + " scored " + (num1 + num2);
+  }
+
+  return add();
+}
+
+getScore(); // Returns "Chamahk scored 5"
+ +

Kapsam ve fonksiyon yığını

+ +

Yineleme

+ +

Bir fonksiyon kendisine başvurabilir ve kendisini arayabilir. Bir işlevin kendisine başvurması için üç yol vardır:

+ +

 

+ +
    +
  1. fonksiyonun adı
  2. +
  3. arguments.callee
  4. +
  5. +

    fonksiyona başvuran bir kapsam içi değişken  

    +
  6. +
+ +
+
+
+

Örneğin, aşağıdaki işlev tanımını göz önünde bulundurun:

+
+
+
+ +

 

+ +
var foo = function bar() {
+   // statements go here
+};
+
+ +

Fonksiyon gövdesinde aşağıdakilerden hepsi eşdeğerdir.

+ +
    +
  1. bar()
  2. +
  3. arguments.callee()
  4. +
  5. foo()
  6. +
+ +

Kendisini çağıran fonksiyona özyinelemeli fonksiyon denir. Bazı açılardan, özyineleme bir döngüye benzer. Her ikisi de aynı kodu birkaç kez uygular ve her ikisi de bir koşul gerektirir (bu, sonsuz bir döngüden kaçınmak veya daha doğrusu bu durumda sonsuz özyinelemeden kaçınmak için). Örneğin, aşağıdaki döngü:

+ +
var x = 0;
+while (x < 10) { // "x < 10" is the loop condition
+   // do stuff
+   x++;
+}
+
+ +

özyinelemeli bir fonksiyona ve bu fonksiyonun çağrısına dönüştürülebilir:

+ +
function loop(x) {
+  if (x >= 10) // "x >= 10" is the exit condition (equivalent to "!(x < 10)")
+    return;
+  // do stuff
+  loop(x + 1); // the recursive call
+}
+loop(0);
+
+ +

Ancak, bazı algoritmalar basit yinelemeli döngüler olamaz. Örneğin, bir ağaç yapısının tüm düğümlerinin (örneğin DOM) alınması özyineleme kullanılarak daha kolay yapılır:

+ +
function walkTree(node) {
+  if (node == null) //
+    return;
+  // do something with node
+  for (var i = 0; i < node.childNodes.length; i++) {
+    walkTree(node.childNodes[i]);
+  }
+}
+
+ +

Fonksiyon döngüsü ile karşılaştırıldığında, her özyinelemeli çağrının kendisi burada birçok özyinelemeli çağrı yapar.

+ +

Herhangi bir özyinelemeli algoritmayı özyinelemeli olmayan bir algoritmaya dönüştürmek mümkündür, ancak çoğu zaman mantık çok daha karmaşıktır ve bunu yapmak bir yığının kullanılmasını gerektirir. Aslında, özyinelemenin kendisi bir yığın kullanır: Fonksiyon yığını.

+ +

Yığın benzeri davranış aşağıdaki örnekte görülebilir:

+ +
function foo(i) {
+  if (i < 0)
+    return;
+  console.log('begin:' + i);
+  foo(i - 1);
+  console.log('end:' + i);
+}
+foo(3);
+
+// Output:
+
+// begin:3
+// begin:2
+// begin:1
+// begin:0
+// end:0
+// end:1
+// end:2
+// end:3
+ +

Nested functions and closures

+ +

You can nest a function within a function. The nested (inner) function is private to its containing (outer) function. It also forms a closure. A closure is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).

+ +

Since a nested function is a closure, this means that a nested function can "inherit" the arguments and variables of its containing function. In other words, the inner function contains the scope of the outer function.

+ +

To summarize:

+ + + + + +

The following example shows nested functions:

+ +
function addSquares(a,b) {
+  function square(x) {
+    return x * x;
+  }
+  return square(a) + square(b);
+}
+a = addSquares(2,3); // returns 13
+b = addSquares(3,4); // returns 25
+c = addSquares(4,5); // returns 41
+
+ +

Since the inner function forms a closure, you can call the outer function and specify arguments for both the outer and inner function:

+ +
function outside(x) {
+  function inside(y) {
+    return x + y;
+  }
+  return inside;
+}
+fn_inside = outside(3); // Think of it like: give me a function that adds 3 to whatever you give it
+result = fn_inside(5); // returns 8
+
+result1 = outside(3)(5); // returns 8
+
+ +

Preservation of variables

+ +

Notice how x is preserved when inside is returned. A closure must preserve the arguments and variables in all scopes it references. Since each call provides potentially different arguments, a new closure is created for each call to outside. The memory can be freed only when the returned inside is no longer accessible.

+ +

This is not different from storing references in other objects, but is often less obvious because one does not set the references directly and cannot inspect them.

+ +

Multiply-nested functions

+ +

Functions can be multiply-nested, i.e. a function (A) containing a function (B) containing a function (C). Both functions B and C form closures here, so B can access A and C can access B. In addition, since C can access B which can access A, C can also access A. Thus, the closures can contain multiple scopes; they recursively contain the scope of the functions containing it. This is called scope chaining. (Why it is called "chaining" will be explained later.)

+ +

Consider the following example:

+ +
function A(x) {
+  function B(y) {
+    function C(z) {
+      console.log(x + y + z);
+    }
+    C(3);
+  }
+  B(2);
+}
+A(1); // logs 6 (1 + 2 + 3)
+
+ +

In this example, C accesses B's y and A's x. This can be done because:

+ +
    +
  1. B forms a closure including A, i.e. B can access A's arguments and variables.
  2. +
  3. C forms a closure including B.
  4. +
  5. Because B's closure includes A, C's closure includes A, C can access both B and A's arguments and variables. In other words, C chains the scopes of B and A in that order.
  6. +
+ +

The reverse, however, is not true. A cannot access C, because A cannot access any argument or variable of B, which C is a variable of. Thus, C remains private to only B.

+ +

Name conflicts

+ +

When two arguments or variables in the scopes of a closure have the same name, there is a name conflict. More inner scopes take precedence, so the inner-most scope takes the highest precedence, while the outer-most scope takes the lowest. This is the scope chain. The first on the chain is the inner-most scope, and the last is the outer-most scope. Consider the following:

+ +
function outside() {
+  var x = 10;
+  function inside(x) {
+    return x;
+  }
+  return inside;
+}
+result = outside()(20); // returns 20 instead of 10
+
+ +

The name conflict happens at the statement return x and is between inside's parameter x and outside's variable x. The scope chain here is {inside, outside, global object}. Therefore inside's x takes precedences over outside's x, and 20 (inside's x) is returned instead of 10 (outside's x).

+ +

Closures

+ +

Closures are one of the most powerful features of JavaScript. JavaScript allows for the nesting of functions and grants the inner function full access to all the variables and functions defined inside the outer function (and all other variables and functions that the outer function has access to). However, the outer function does not have access to the variables and functions defined inside the inner function. This provides a sort of security for the variables of the inner function. Also, since the inner function has access to the scope of the outer function, the variables and functions defined in the outer function will live longer than the outer function itself, if the inner function manages to survive beyond the life of the outer function. A closure is created when the inner function is somehow made available to any scope outside the outer function.

+ +
var pet = function(name) {   // The outer function defines a variable called "name"
+  var getName = function() {
+    return name;             // The inner function has access to the "name" variable of the outer function
+  }
+  return getName;            // Return the inner function, thereby exposing it to outer scopes
+}
+myPet = pet("Vivie");
+
+myPet();                     // Returns "Vivie"
+
+ +

It can be much more complex than the code above. An object containing methods for manipulating the inner variables of the outer function can be returned.

+ +
var createPet = function(name) {
+  var sex;
+
+  return {
+    setName: function(newName) {
+      name = newName;
+    },
+
+    getName: function() {
+      return name;
+    },
+
+    getSex: function() {
+      return sex;
+    },
+
+    setSex: function(newSex) {
+      if(typeof newSex === "string" && (newSex.toLowerCase() === "male" || newSex.toLowerCase() === "female")) {
+        sex = newSex;
+      }
+    }
+  }
+}
+
+var pet = createPet("Vivie");
+pet.getName();                  // Vivie
+
+pet.setName("Oliver");
+pet.setSex("male");
+pet.getSex();                   // male
+pet.getName();                  // Oliver
+
+ +

In the code above, the name variable of the outer function is accessible to the inner functions, and there is no other way to access the inner variables except through the inner functions. The inner variables of the inner functions act as safe stores for the outer arguments and variables. They hold "persistent", yet secure, data for the inner functions to work with. The functions do not even have to be assigned to a variable, or have a name.

+ +
var getCode = (function(){
+  var secureCode = "0]Eal(eh&2";    // A code we do not want outsiders to be able to modify...
+
+  return function () {
+    return secureCode;
+  };
+})();
+
+getCode();    // Returns the secureCode
+
+ +

There are, however, a number of pitfalls to watch out for when using closures. If an enclosed function defines a variable with the same name as the name of a variable in the outer scope, there is no way to refer to the variable in the outer scope again.

+ +
var createPet = function(name) {  // Outer function defines a variable called "name"
+  return {
+    setName: function(name) {    // Enclosed function also defines a variable called "name"
+      name = name;               // ??? How do we access the "name" defined by the outer function ???
+    }
+  }
+}
+
+ +

The magical this variable is very tricky in closures. They have to be used carefully, as what this refers to depends completely on where the function was called, rather than where it was defined.

+ +

Using the arguments object

+ +

The arguments of a function are maintained in an array-like object. Within a function, you can address the arguments passed to it as follows:

+ +
arguments[i]
+
+ +

where i is the ordinal number of the argument, starting at zero. So, the first argument passed to a function would be arguments[0]. The total number of arguments is indicated by arguments.length.

+ +

Using the arguments object, you can call a function with more arguments than it is formally declared to accept. This is often useful if you don't know in advance how many arguments will be passed to the function. You can use arguments.length to determine the number of arguments actually passed to the function, and then access each argument using the arguments object.

+ +

For example, consider a function that concatenates several strings. The only formal argument for the function is a string that specifies the characters that separate the items to concatenate. The function is defined as follows:

+ +
function myConcat(separator) {
+   var result = ""; // initialize list
+   var i;
+   // iterate through arguments
+   for (i = 1; i < arguments.length; i++) {
+      result += arguments[i] + separator;
+   }
+   return result;
+}
+
+ +

You can pass any number of arguments to this function, and it concatenates each argument into a string "list":

+ +
// returns "red, orange, blue, "
+myConcat(", ", "red", "orange", "blue");
+
+// returns "elephant; giraffe; lion; cheetah; "
+myConcat("; ", "elephant", "giraffe", "lion", "cheetah");
+
+// returns "sage. basil. oregano. pepper. parsley. "
+myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley");
+
+ +
+

Note: The arguments variable is "array-like", but not an array. It is array-like in that is has a numbered index and a length property. However, it does not possess all of the array-manipulation methods.

+
+ +

See the {{jsxref("Function")}} object in the JavaScript reference for more information.

+ +

Function parameters

+ +

Starting with ECMAScript 6, there are two new kinds of parameters: default parameters and rest parameters.

+ +

Default parameters

+ +

In JavaScript, parameters of functions default to undefined. However, in some situations it might be useful to set a different default value. This is where default parameters can help.

+ +

In the past, the general strategy for setting defaults was to test parameter values in the body of the function and assign a value if they are undefined. If in the following example, no value is provided for b in the call, its value would be undefined  when evaluating a*b and the call to multiply would have returned NaN. However, this is caught with the second line in this example:

+ +
function multiply(a, b) {
+  b = typeof b !== 'undefined' ?  b : 1;
+
+  return a*b;
+}
+
+multiply(5); // 5
+
+ +

With default parameters, the check in the function body is no longer necessary. Now, you can simply put 1 as the default value for b in the function head:

+ +
function multiply(a, b = 1) {
+  return a*b;
+}
+
+multiply(5); // 5
+ +

Fore more details, see default parameters in the reference.

+ +

Rest parameters

+ +

The rest parameter syntax allows us to represent an indefinite number of arguments as an array. In the example, we use the rest parameters to collect arguments from the second one to the end. We then multiply them by the first one. This example is using an arrow function, which is introduced in the next section.

+ +
function multiply(multiplier, ...theArgs) {
+  return theArgs.map(x => multiplier * x);
+}
+
+var arr = multiply(2, 1, 2, 3);
+console.log(arr); // [2, 4, 6]
+ +

Arrow functions

+ +

An arrow function expression (also known as fat arrow function) has a shorter syntax compared to function expressions and lexically binds the this value. Arrow functions are always anonymous. See also this hacks.mozilla.org blog post: "ES6 In Depth: Arrow functions".

+ +

Two factors influenced the introduction of arrow functions: shorter functions and lexical this.

+ +

Shorter functions

+ +

In some functional patterns, shorter functions are welcome. Compare:

+ +
var a = [
+  "Hydrogen",
+  "Helium",
+  "Lithium",
+  "Beryllium"
+];
+
+var a2 = a.map(function(s){ return s.length });
+
+console.log(a2); // logs [ 8, 6, 7, 9 ]
+
+var a3 = a.map( s => s.length );
+
+console.log(a3); // logs [ 8, 6, 7, 9 ]
+
+ +

Lexical this

+ +

Until arrow functions, every new function defined its own this value (a new object in case of a constructor, undefined in strict mode function calls, the context object if the function is called as an "object method", etc.). This proved to be annoying with an object-oriented style of programming.

+ +
function Person() {
+  // The Person() constructor defines `this` as itself.
+  this.age = 0;
+
+  setInterval(function growUp() {
+    // In nonstrict mode, the growUp() function defines `this`
+    // as the global object, which is different from the `this`
+    // defined by the Person() constructor.
+    this.age++;
+  }, 1000);
+}
+
+var p = new Person();
+ +

In ECMAScript 3/5, this issue was fixed by assigning the value in this to a variable that could be closed over.

+ +
function Person() {
+  var self = this; // Some choose `that` instead of `self`.
+                   // Choose one and be consistent.
+  self.age = 0;
+
+  setInterval(function growUp() {
+    // The callback refers to the `self` variable of which
+    // the value is the expected object.
+    self.age++;
+  }, 1000);
+}
+ +

Alternatively, a bound function could be created so that the proper this value would be passed to the growUp() function.

+ +

Arrow functions capture the this value of the enclosing context, so the following code works as expected.

+ +
function Person(){
+  this.age = 0;
+
+  setInterval(() => {
+    this.age++; // |this| properly refers to the person object
+  }, 1000);
+}
+
+var p = new Person();
+ +

Predefined functions

+ +

JavaScript has several top-level, built-in functions:

+ +
+
{{jsxref("Global_Objects/eval", "eval()")}}
+
+

The eval() method evaluates JavaScript code represented as a string.

+
+
{{jsxref("Global_Objects/uneval", "uneval()")}} {{non-standard_inline}}
+
+

The uneval() method creates a string representation of the source code of an {{jsxref("Object")}}.

+
+
{{jsxref("Global_Objects/isFinite", "isFinite()")}}
+
+

The global isFinite() function determines whether the passed value is a finite number. If needed, the parameter is first converted to a number.

+
+
{{jsxref("Global_Objects/isNaN", "isNaN()")}}
+
+

The isNaN() function determines whether a value is {{jsxref("Global_Objects/NaN", "NaN")}} or not. Note: coercion inside the isNaN function has interesting rules; you may alternatively want to use {{jsxref("Number.isNaN()")}}, as defined in ECMAScript 6, or you can use typeof to determine if the value is Not-A-Number.

+
+
{{jsxref("Global_Objects/parseFloat", "parseFloat()")}}
+
+

The parseFloat() function parses a string argument and returns a floating point number.

+
+
{{jsxref("Global_Objects/parseInt", "parseInt()")}}
+
+

The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).

+
+
{{jsxref("Global_Objects/decodeURI", "decodeURI()")}}
+
+

The decodeURI() function decodes a Uniform Resource Identifier (URI) previously created by {{jsxref("Global_Objects/encodeURI", "encodeURI")}} or by a similar routine.

+
+
{{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent()")}}
+
+

The decodeURIComponent() method decodes a Uniform Resource Identifier (URI) component previously created by {{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent")}} or by a similar routine.

+
+
{{jsxref("Global_Objects/encodeURI", "encodeURI()")}}
+
+

The encodeURI() method encodes a Uniform Resource Identifier (URI) by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).

+
+
{{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent()")}}
+
+

The encodeURIComponent() method encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).

+
+
{{jsxref("Global_Objects/escape", "escape()")}} {{deprecated_inline}}
+
+

The deprecated escape() method computes a new string in which certain characters have been replaced by a hexadecimal escape sequence. Use {{jsxref("Global_Objects/encodeURI", "encodeURI")}} or {{jsxref("Global_Objects/encodeURIComponent", "encodeURIComponent")}} instead.

+
+
{{jsxref("Global_Objects/unescape", "unescape()")}} {{deprecated_inline}}
+
+

The deprecated unescape() method computes a new string in which hexadecimal escape sequences are replaced with the character that it represents. The escape sequences might be introduced by a function like {{jsxref("Global_Objects/escape", "escape")}}. Because unescape() is deprecated, use {{jsxref("Global_Objects/decodeURI", "decodeURI()")}} or {{jsxref("Global_Objects/decodeURIComponent", "decodeURIComponent")}} instead.

+
+
+ +

{{PreviousNext("Web/JavaScript/Guide/Loops_and_iteration", "Web/JavaScript/Guide/Expressions_and_Operators")}}

diff --git a/files/tr/web/javascript/guide/ifadeler/index.html b/files/tr/web/javascript/guide/ifadeler/index.html deleted file mode 100644 index dcf6d13466..0000000000 --- a/files/tr/web/javascript/guide/ifadeler/index.html +++ /dev/null @@ -1,419 +0,0 @@ ---- -title: Kontrol akışı ve hata yakalama -slug: Web/JavaScript/Guide/Ifadeler -tags: - - Başlangıç - - JavaScript - - Rehberi -translation_of: Web/JavaScript/Guide/Control_flow_and_error_handling ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Grammar_and_types", "Web/JavaScript/Guide/Loops_and_iteration")}}
- -

JavaScript, uygulamanızın etkilişim halinde olmasını sağlayan kontrol akışı ifadeleri gibi birçok ifadeyi destekler. Bu bölümde, bu ifadeler üzerine durulacaktır.

- -

En basit olarak anlatmak gerekirse, JavaScript tarafından çalıştırılacak her komuta ifade adı verilir. Noktalı virgül (;) karakteri ise, JavaScript kodundaki ifadelerin birbirinden ayrılması için kullanılmaktadır.

- -

Blok ifadesi

- -

En temel ifade türü, ifadelerin gruplanmasını sağlayan blok ifadesidir. Blok ifadesi,  bir çift süslü parantezle sınırlandırılır:

- -
{ ifade_1; ifade_2; . . . ifade_n; }
-
- -

Örnek

- -

Blok ifadeleri genellikle kontrol akışı ifadeleri ile birlikte kullanılır (örn: if, for, while).

- -
while (x < 10) {
-  x++;
-}
-
- -

Buradaki, { x++; } bir blok ifadesidir.

- -

Önemli: ECMAScript2015'ten önceki JavaScript'te blok etki alanı bulunmamaktadır. Blok içerisinde yer alan değişkenlerin etki alanı, onları içeren fonksiyon veya .js dosyası kadar geniş bir alanı kapsar, ve bu değişkenler üzerinde yapılan değişiklikler bloğun ötesinde de kalıcılık gösterir. Başka bir deyişle blok ifadeleri, değişkenler için bir etki alanı oluşturmazlar. C ve Java dilinden aşina olduğunuz değişkenden bağımsız blok ifadeleri, JavaScript'te tamamıyla farklı bir davranış sergileyebilirler. Aşağıdaki örneği inceleyelim:

- -
var x = 1;
-{
-  var x = 2;
-}
-console.log(x); // Ekrandaki çıktı: 2
-
- -

Kodun çıktısı 2 olacaktır. Çünkü blok içerisindeki var x ifadesi  ile bloktan önce gelen var x ifadesi aynı etki alanı içerisindedir. Eğer üstteki kod C veya Java dilinde olsaydı, ekrandaki çıktı 1 olacaktı.

- -

ECMAScript 6 ile birlikte gelen let tanımıyla oluşturulan değişkenler, blok seviyesinde etki alanına sahiptir. Daha fazla bilgi için {{jsxref("Statements/let", "let")}} sayfasına bakınız.

- -

Koşullu ifadeler

- -

Belirli bir koşul sağlandığında çalışacak komutlar kümesine koşullu ifade denilir. JavaScript, iki adet koşullu ifadeyi destekler: if...else ve switch.

- -

if...else ifadesi

- -

Belirli bir mantıksal durum sağlandığında bir ifadenin çalıştırılması için if ifadesi kullanılır. Mantıksal durum sağlanmadığında çalıştırılacak komutlar için ise else kelimesi kullanıılabilir. Bir if ifadesi aşağıdaki şekilde oluşturulur:

- -
if (mantıksal_durum) {
-  ifade_1;
-} else {
-  ifade_2;
-}
- -

mantıksal_durum, true veya false değerler alabilen herhangi bir ifade olabilir. Eğer mantıksal_durum, true olursa ifade_1 çalışacak; aksi halde, ifade_2 is çalışacaktır. ifade_1 ve ifade_2 ifadeleri, çalıştırılacak herhangi bir ifade olabilir.

- -

Birçok mantıksal durumun kontrolünün bütün bir halde yapılabilmesi için aşağıdaki şekilde else if tanımlamalarını kullanabilirsiniz.

- -
if (mantıksal_durum_1) {
-  ifade_1;
-} else if (mantıksal_durum_2) {
-  ifade_2;
-} else if (mantıksal_durum_n) {
-  ifade_n;
-} else {
-  ifade_son;
-}
-
- -

Üstteki gibi çoklu mantıksal durumların olduğu ifadelerde,  yalnızca true olan ilk mantıksal durum çalıştırılır, ilişkili diğer kontrol ifadeleri çalıştırılmaz. Birçok ifadenin çalıştırılması için ifadeler, blok ifadesi ({ ... }) içerisinde gruplandırılır. Özellikle iç içe if ifadelerinin olduğu durumlar başta olmak üzere blok ifadeleri, geliştiriciler arasında yaygın olarak kullanılmaktadır:

- -
if (mantıksal_durum) {
-  eğer_durum_true_ise_çalışacak_ifade_1;
-  eğer_durum_true_ise_çalışacak_ifade_2;
-} else {
-  eğer_durum_false_ise_çalışacak_ifade_3;
-  eğer_durum_false_ise_çalışacak_ifade_4;
-}
-
- -
mantıksal_durum kısmında herhangi bir değişkene değer atamak yanlış bir kullanımdır, çünkü kodunuza sizden sonra bakan biri atama işlemini ilk bakışta eşitlik olarak görebilir. Örneğin aşağıdaki şekilde bir kullanım yanlıştır:
- -
- -
if (x = y) {
-  /* diğer ifadeler */
-}
-
- -

Eğer mantıksal_durum kısmında gerçekten atama yapmanız gerekiyorsa, bunu yapmanın en iyi yolu atama ifadesini parantezler içerisine almaktır. Örneğin:

- -
if ((x = y)) {
-  /* diğer ifadeler */
-}
-
- -

Yanlışımsı (falsy) değerler

- -

Aşağıdaki değerler JavaScript tarafından false olarak değerlendirilir ve ({{Glossary("Falsy")}} değerler olarak bilinir):

- - - -

Mantıksal durum içerisine alınan diğer bütün değerler ve nesneler, JavaScript tarafından true olarak değerlendirilir.

- -

{{jsxref("Boolean")}} nesnesindeki true ve false ile ilkel tipteki true ve false değerlerini karıştırmayınız. Örneğin:

- -
var b = new Boolean(false);
-if (b) // bu ifade true olarak değerlendirilir
-
- -

Örnek

- -

Aşağıdaki örnekte bulunan checkData fonksiyonu, HTML dokümanındaki formda yer alan ikiKarakter isimli girdi nesnesine ait değerin, karakter sayısı 2 ise true döndürülür, değilse ekrana bir uyarı metni basılır ve false döndürülür:

- -
function checkData() {
-  if (document.form1.ikiKarakter.value.length == 2) {
-    return true;
-  } else {
-    alert("Tam olarak iki karakter giriniz. " +
-    document.form1.ikiKarakter.value + " geçersizdir.");
-    return false;
-  }
-}
-
- -

switch ifadesi

- -

Bir switch ifadesine, mantıksal bir ifade verilir ve bu ifade ile eşleşen bir etiket varsa, etiketi içeren case ifadesi çalıştırılır, yoksa varsayılan ifade (default) çalıştırılır. Örnek:

- -
switch (mantıksal_ifade) {
-  case etiket_1:
-    ifadeler_1
-    [break;]
-  case etiket_2:
-    ifadeler_2
-    [break;]
-    ...
-  default:
-    varsayılan_ifadeler
-    [break;]
-}
-
- -

Üstteki kodu çalıştırırken JavaScript, mantıksal_ifade ile eşleşen etikete sahip case cümleciğini arar ve ilişkili ifadeleri çalıştırır. Eğer eşleşen hiçbir etiket bulunamadıysa, default cümleciğinin olup olmadığına bakar, varsa ve ilgili varsayılan ifadeleri çalıştırır. Eğer default cümleciği de yoksa, switch bloğundan çıkılır.  default cümleciğinin sırası önemli olmamakla birlikte, genel kullanımlarda hep en sonda yer almaktadır.

- -

Her case cümleciğinde, isteğe bağlı olarak konulan break ifadesi,  eşleşen ifadenin çalıştırılıp tamamlandıktan sonra switch bloğundan çıkmayı sağlar. Eğer break ifadesi yazılmazsa, program switch ifadesi içerisindeki bir sonraki case ifadesini çalıştırarak yoluna devam eder. 

- -

Örnek

- -

Aşağıdaki örnekte, meyve ifadesinin değeri "Muz" ise,  program "Muz" değeri ile eşleşen case "Muz" ifadesini çalıştırır. break ile karşılaşıldığında, program switch bloğundan çıkar ve switch bloğundan sonraki kodları çalıştırır. Eğer break ifadesi olmasaydı, "Muz" ile alakasız olan, case "Kiraz" ifadesi de çalıştırılacaktı.

- -
switch (meyve) {
-  case "Portakal":
-    console.log("Portakalların kilosu ₺1.99 lira.");
-    break;
-  case "Elma":
-    console.log("Elmaların kilosu ₺1.49 lira.");
-    break;
-  case "Muz":
-    console.log("Muzların kilosu ₺2.49 lira.");
-    break;
-  case "Kiraz":
-    console.log("Kirazların kilosu ₺2.19 lira.");
-    break;
-  case "Çilek":
-    console.log("Çileklerin kilosu ₺2.49 lira.");
-    break;
-  case "Avokado":
-    console.log("Avokadoların kilosu ₺5.99 lira.");
-    break;
-  default:
-   console.log("Maalesef elimizde hiç " + meyve + " kalmadı.");
-}
-console.log("Başka bir şey lazım mı?");
- -

Exception (Hata) yakalama ifadeleri

- -

throw ifadesi ile exception fırlatabilir, try...catch ifadeleri kullanarak hata yakalama işlemlerinizi yürütebilirsiniz.

- - - -

Exception türleri

- -

JavaScript'te neredeyse her nesne fırlatılabilir. Buna rağmen fırlatılacak türdeki nesnelerin hepsi aynı şekilde oluşturulmamışlardır. Sayı ve string değerlerinin hata olarak fırlatılması oldukça yaygın olmasına rağmen, bu amaç için belirli olarak  oluşturulan aşağıdaki exception türlerinden birinin kullanılması daha anlamlıdır:

- - - -

throw ifadesi

- -

Bir exception fırlatmak için throw ifadesini kullanılır. Bir exception fırlattığınız zaman, fırlatılacak ifadeyi de belirlersiniz:

- -
throw ifade;
-
- -

Herhangi bir türdeki ifadeyi exception olarak fırlatabilirsiniz. Aşağıdaki kodda çeşitli türlerdeki exception'lar fırlatılmaktadır:

- -
throw "Hata2";   // String türü
-throw 42;         // Sayı türü
-throw true;       // Boolean türü
-throw { toString: function() { return "Ben bir nesneyim."; } };
-
- -
Not: Bir exception fırlatırken ilgili exception nesnesini belirleyebilirsiniz. Daha sonra catch bloğunda hatayı yakaladığınızda ilgili exception nesnesinin özelliklerine erişebilirsiniz. Aşağıdaki ifadede, KullanıcıHatası sınıfından bir nesne oluşturulmakta, ve throw ifadesinde bu nesne fırlatılmaktadır.
- -
// KullanıcıHatası türünde nesne oluşturuluyor
-function KullanıcıHatası(mesaj){
-  this.mesaj=mesaj;
-  this.adı="KullanıcıHatası";
-}
-
-// Oluşturulan KullanıcıHatası nesnesinin konsola yazıldığında güzel bir
-// ifade yazılması için aşağıdaki şekilde toString() fonksiyonunu override ediyoruz.
-KullanıcıHatası.prototype.toString = function () {
-  return this.adı+ ': "' + this.mesaj+ '"';
-}
-
-// KullanıcıHatası nesnesi yaratılır ve exception olarak fırlatılır
-throw new KullanıcıHatası("Yanlış bir değer girdiniz.");
- -

try...catch ifadesi

- -

try...catch ifadesi, çalıştırılması istenen ifadeleri bir blokta tutar. Fırlatılacak exception için bir veya daha fazla ifade belirlenerek, oluşacak bir try...catch ifadesi tarafından yakalanması sağlanır.

- -

try...catch ifadesi, çalıştırılacak bir veya daha fazla komutun yer aldığı, ve try bloğu içerisinde hata oluştuğunda çalışacak ifadeleri içeren, 0 veya daha fazla catch ifadesinin yer aldığı bir try bloğu içerir. Bu şekilde, try içerisinde yer alan başarıyla çalışmasını istediğiniz kodlarda bir sorun oluştuğunda, catch bloğunda bu sorunun üstesinden gelecek kontrolleri yazabilirsiniz. Eğer try bloğu içerisindeki herhangi bir ifade (veya try bloğu içerisinden çağırılan fonksiyon) bir exception fırlatırsa, JavaScript anında catch bloğuna bakar. Eğer try bloğu içerisinde bir exception fırlatılmazsa, catch bloğu çalıştırılmaz ve atlanır. try ve catch bloklarından sonra, eğer varsa finally bloğu da çalıştırılır.

- -

Aşağıdaki örnekte bir try...catch ifadesi kullanılmaktadır. Fonksiyonda, parametre olarak geçilen ay sayısı değeri baz alınarak, diziden ilgili ayın adı getirilmektedir. Eğer ay sayısı değeri 1-12 arasında değilse, "Geçersiz ay sayısı." değeri exception olarak fırlatılır. catch bloğundaki ayAdı değişkeni de "bilinmeyen" olarak atanır.

- -
function getAyAdı(aySayisi) {
-  aySayisi= aySayisi-1; // Dizi indeksi için aySayisi 1 azaltılır (1=Oca, 12=Ara)
-  var aylar= ["Oca","Şub","Mar","Nis","May","Haz","Tem",
-                "Ağu","Eyl","Eki","Kas","Ara"];
-  if (aylar[aySayisi] != null) {
-    return aylar[aySayisi];
-  } else {
-    throw "Geçersiz ay sayısı."; // burada throw ifadesi kullanılıyor
-  }
-}
-
-try { // denenecek ifadeler
-  ayAdı = getAyAdı(aySayim); // function could throw exception
-}
-catch (e) {
-  ayAdı = "bilinmiyor";
-  hatalarımıKaydet(e); // hataların kaydedilmesi için exception nesnesi geçiliyor.
-}
-
- -

catch bloğu

- -

try bloğunda oluşturulan tüm exception'ların yakalanması için catch bloğunu kullanabilirsiniz.

- -
catch (exceptionDeğişkeni) {
-  ifadeler
-}
-
- -

catch bloğunda, throw ifadesi tarafından belirlenecek değerin tutulması için bir değişken tanımlanır; bu değişken kullanılarak, fırlatılan exception ile ilgili bilgiler elde edilmiş olur. catch bloğuna girildiğinde JavaScript, bu değişkenin içini doldurur; değişken değeri sadece catch bloğu süresince geçerli kalır; catch bloğu çalışmasını tamamladığında değişken artık mevcut değildir.

- -

Örneğin aşağıdaki kodda, bir exception fırlatılıyor, ve fırlatıldığı anda otomatik olarak catch bloğuna iletiliyor.

- -
try {
-  throw "hata" // bir exception oluşturur.
-}
-catch (e) {
-  // herhangi bir exception'ı yakalamak için oluşturulan ifadeler
-  hatalarımıKaydet(e) // hataların kaydedilmesi için exception nesnesi geçilir.
-}
-
- -

finally bloğu

- -

finally bloğu, try...catch ifadesinden sonra çalıştırılacak kod satırlarını içerir. finally bloğu, hata olsun veya olmasın çalışır. Eğer hata olmuşsa ve exception fırlatılmışsa, bu hatayı karşılayacak catch bloğu olmasa dahi finally bloğu çalışır. 

- -

finally bloğu, hata oluştuğunda bu hataya sebep olan değişkenin kullandığı kaynakların sisteme geri verilmesi için en iyi yerdir. Bu şekilde hata tüm ayrıntılarıyla çözülmüş olur. Aşağıdaki örnekte bir dosya açılmakta, ve sonrasında dosyaya yazma işlemleri için kullanan ifadeler çalıştırılmaktadır (Sunucu taraflı yazılmış koddur. İstemci tarafında dosyaya yazma işlemleri güvenlik açısından engellenmiştir. Eğer dosya, yazmak için açılırken bir exception fırlatılırsa, kod hata vermeden önce finally bloğu çalışır ve erişilecek dosyayı kapatır.

- -
dosyaAç();
-try {
-  dosyayaYaz(veriler); // Bu kısım hata verebilir
-} catch(e) {
-  hatayıKaydetveGöster(e); // Hata ile ilgili bilgiler kaydedilir ve kullanıcıya bir hata mesajı sunulur.
-} finally {
-  dosyayıKapat(); // Dosyayı kapatır (hata olsa da olmasa da).
-}
-
- -

Eğer finally bloğu bir değer geri döndürürse,  bu değer, try ve catch içerisindeki return ifadelerine bakmaksızın, try-catch-finally ifadesinin tamamı için geri dönüş değeri haline gelir:

- -
function f() {
-  try {
-    console.log(0);
-    throw "hata";
-  } catch(e) {
-    console.log(1);
-    return true; // Buradaki return ifadesi,
-                 // finally bloğu tamamlanana dek duraklatılır.
-    console.log(2); // Üstteki return ifadesinden dolayı çalıştırılmaz.
-  } finally {
-    console.log(3);
-    return false; // catch kısmındaki return ifadesinin üstüne yazar ve geçersiz hale getirir.
-    console.log(4); // return'den dolayı çalıştırılmaz.
-  }
-  // Şimdi "return false" ifadesi çalıştırılır ve fonksiyondan çıkılır.
-  console.log(5); // Çalıştırılmaz.
-}
-f(); // Konsola 0 1 3 yazar ve false değerini döndürür.
-
- -

finally bloğunun, geri dönüş değerlerinin üstüne yazma etkisi, aynı zamanda catch bloğu içerisindeki exception'lar için de aynı şekilde çalışır:

- -
function f() {
-  try {
-    throw "hata";
-  } catch(e) {
-    console.log('İçerideki "hata" yakalandı.');
-    throw e; // Burası finally bloğu tamamlanana dek duraklatılır.
-  } finally {
-    return false; // Önceki "throw" ifadesinin üstüne yazar ve
-                  //  throw ifadesini geçersiz hale getirir.
-  }
-  // Şimdi "return false" ifadesi çalıştırılır.
-}
-
-try {
-  f();
-} catch(e) {
-  // f() fonksiyonundaki throw ifadesi geçersiz hale geldiği için
-  //  buradaki catch bloğu çalıştırılmaz.
-  console.log('Diğer "hata" yakalandı.');
-}
-
-// Ekran çıktısı: İçerideki "hata" yakalandı.
- -

İçiçe try...catch ifadeleri

- -

Bir veya daha fazla iç içe try...catch ifadeleri tanımlayabilirsiniz. Eğer içteki try...catch ifadesinin catch bloğu yoksa, bir dıştaki try...catch ifadesinin catch bloğu kontrol edilir.

- -

Error nesnelerinin etkili kullanımı

- -

Error nesnesinin türüne bağlı olarak,  'name' ve 'message' özellikleri vasıtasıyla daha anlamlı hata mesajları tanımlayabilirsiniz. 'name' özelliği, oluşan hatayı sınıflandırır (örn, 'DOMException' veya 'Error'). 'message' ise hata nesnesinin string'e dönüştürülmesine nazaran  genellikle daha kısa bir mesaj sunulmasına olanak tanır.

- -

Eğer kendi exception nesnelerinizi fırlatıyorsanız ve bu özellikleri kullanarak hatayı anlamlı hale getirmek istiyorsanız Error sınıfının yapıcısının getirdiği avantajlardan faydalanabilirsiniz (örneğin catch bloğunuzun, kendi exception'larınız ile sistem exception'ları arasındaki farkı ayırt edemediği gibi durumlarda). Aşağıdaki örneği inceleyelim:

- -
function hatayaMeyilliFonksiyon() {
-  if (hataVerenFonksiyonumuz()) {
-    throw (new Error('Hata oluştu'));
-  } else {
-    sistemHatasıVerenFonksiyon();
-  }
-}
-
-try {
-  hatayaMeyilliFonksiyon();
-}
-catch (e) {
-  console.log(e.name); // 'Error' yazar
-  console.log(e.message); // 'Hata oluştu' veya bir JavaScript hata mesajı yazar
-}
- -

Promise nesneleri

- -

ECMAScript2015 ile birlikte JavaScript'e, asenkron ve geciktirilmiş işlemlerin akış kontrolünün sağlanması için {{jsxref("Promise")}} nesneleri gelmiştir.

- -

Bir Promise nesnesi aşağıdaki durumlardan birinde bulunur:

- - - -

- -

XHR ile resim yükleme

- -

Promise ve XMLHttpRequest kullanarak bir resmin yüklenmesi için MDN GitHub promise-test sayfasında basit bir örnek mevcuttur. Ayrıca örneği canlı olarak da görebilirsiniz. Örnekteki her aşamaya yorum satırları eklenmiştir. Bu sayede Promise ve XHR mimarisini daha yakından izleyebilirsiniz. Aşağıda Promise nesnesinin akışını gösteren örneğin belgelendirilmemiş sürümü bulunmaktadır:

- -
function resimYükle(url) {
-  return new Promise(function(başarıSonucundaFonk, hataSonucundaFonk) {
-    var istek = new XMLHttpRequest();
-    istek.open('GET', url);
-    istek.responseType = 'blob';
-    istek.onload = function() {
-      if (istek.status === 200) {
-        başarıSonucundaFonk(istek.cevabı);
-      } else {
-        hataSonucundaFonk(Error('Resim yüklenemedi; hata kodu:'
-                     + istek.hataKodu));
-      }
-    };
-    istek.onerror = function() {
-      hataSonucundaFonk(Error('Bir bağlantı hatası oluştu.'));
-    };
-    istek.send();
-  });
-}
- -

Daha fazla detaylı bilgi için {{jsxref("Promise")}} sayfasına bakınız.

- -
{{PreviousNext("Web/JavaScript/Guide/Grammar_and_types", "Web/JavaScript/Guide/Loops_and_iteration")}}
diff --git "a/files/tr/web/javascript/guide/nesneler_ile_\303\247al\304\261\305\237mak/index.html" "b/files/tr/web/javascript/guide/nesneler_ile_\303\247al\304\261\305\237mak/index.html" deleted file mode 100644 index 0782b4db6c..0000000000 --- "a/files/tr/web/javascript/guide/nesneler_ile_\303\247al\304\261\305\237mak/index.html" +++ /dev/null @@ -1,504 +0,0 @@ ---- -title: Nesnelerle çalışmak -slug: Web/JavaScript/Guide/Nesneler_ile_çalışmak -translation_of: Web/JavaScript/Guide/Working_with_Objects ---- -
{{jsSidebar("JavaScript Rehberi")}} {{PreviousNext("Web/JavaScript/Guide/Keyed_collections", "Web/JavaScript/Guide/Details_of_the_Object_Model")}}
- -

JavaScript basit bir nesne tabanlı paradigmada tasarlanmıştır. Bir nesne bir özellikler koleksiyonudur ve bir özellik bir ad (veya anahtar) ile bir değer arasındaki ilişkidir. Bir özelliğin değeri bir fonksiyon olabilir, bu durumda özellik bir metod olarak bilinir. Tarayıcıda önceden tanımlanmış olan nesnelere ek olarak, kendi nesnelerinizi de tanımlayabilirsiniz. Bu bölümde, nesnelerin, özelliklerin, fonksiyonların ve metodların nasıl kullanıldığı ve kendi nesnelerinizin nasıl oluşturulacağı açıklanmaktadır.

- -

Nesnelere genel bakış

- -

JavaScript'teki nesneler, diğer birçok programlama dilinde olduğu gibi, gerçek hayattaki nesnelerle karşılaştırılabilir. JavaScript'teki nesneler kavramı gerçek hayattaki somut nesnelerle anlaşılabilir.

- -

JavaScript'te bir nesne, özellikleri ve tipiyle bağımsız bir varlıktır. Örneğin bir fincanla karşılaştırın. Bir fincan, özellikleri olan bir nesnedir. Bir fincan bir renge, bir tasarıma, ağırlığa, yapıldığı bir malzemeye vs. sahiptir. Aynı şekilde, JavaScript nesnelerinin de özelliklerini tanımlayan özellikleri olabilir.

- -

Nesneler ve özellikleri

- -

A JavaScript object has properties associated with it. A property of an object can be explained as a variable that is attached to the object. Object properties are basically the same as ordinary JavaScript variables, except for the attachment to objects. The properties of an object define the characteristics of the object. You access the properties of an object with a simple dot-notation:

- -
objectName.propertyName
-
- -

Like all JavaScript variables, both the object name (which could be a normal variable) and property name are case sensitive. You can define a property by assigning it a value. For example, let's create an object named myCar and give it properties named make, model, and year as follows:

- -
var myCar = new Object();
-myCar.make = 'Ford';
-myCar.model = 'Mustang';
-myCar.year = 1969;
-
- -

Unassigned properties of an object are {{jsxref("undefined")}} (and not {{jsxref("null")}}).

- -
myCar.color; // undefined
- -

Properties of JavaScript objects can also be accessed or set using a bracket notation (for more details see property accessors). Objects are sometimes called associative arrays, since each property is associated with a string value that can be used to access it. So, for example, you could access the properties of the myCar object as follows:

- -
myCar['make'] = 'Ford';
-myCar['model'] = 'Mustang';
-myCar['year'] = 1969;
-
- -

An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation. This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime). Examples are as follows:

- -
// four variables are created and assigned in a single go,
-// separated by commas
-var myObj = new Object(),
-    str = 'myString',
-    rand = Math.random(),
-    obj = new Object();
-
-myObj.type              = 'Dot syntax';
-myObj['date created']   = 'String with space';
-myObj[str]              = 'String value';
-myObj[rand]             = 'Random Number';
-myObj[obj]              = 'Object';
-myObj['']               = 'Even an empty string';
-
-console.log(myObj);
-
- -

Please note that all keys in the square bracket notation are converted to string unless they're Symbols, since JavaScript object property names (keys) can only be strings or Symbols (at some point, private names will also be added as the class fields proposal progresses, but you won't use them with [] form). For example, in the above code, when the key obj is added to the myObj, JavaScript will call the {{jsxref("Object.toString", "obj.toString()")}} method, and use this result string as the new key.

- -

You can also access properties by using a string value that is stored in a variable:

- -
var propertyName = 'make';
-myCar[propertyName] = 'Ford';
-
-propertyName = 'model';
-myCar[propertyName] = 'Mustang';
-
- -

You can use the bracket notation with for...in to iterate over all the enumerable properties of an object. To illustrate how this works, the following function displays the properties of the object when you pass the object and the object's name as arguments to the function:

- -
function showProps(obj, objName) {
-  var result = ``;
-  for (var i in obj) {
-    // obj.hasOwnProperty() is used to filter out properties from the object's prototype chain
-    if (obj.hasOwnProperty(i)) {
-      result += `${objName}.${i} = ${obj[i]}\n`;
-    }
-  }
-  return result;
-}
-
- -

So, the function call showProps(myCar, "myCar") would return the following:

- -
myCar.make = Ford
-myCar.model = Mustang
-myCar.year = 1969
- -

Enumerate the properties of an object

- -

Starting with ECMAScript 5, there are three native ways to list/traverse object properties:

- - - -

Before ECMAScript 5, there was no native way to list all properties of an object. However, this can be achieved with the following function:

- -
function listAllProperties(o) {
-	var objectToInspect;
-	var result = [];
-
-	for(objectToInspect = o; objectToInspect !== null;
-           objectToInspect = Object.getPrototypeOf(objectToInspect)) {
-        result = result.concat(
-            Object.getOwnPropertyNames(objectToInspect)
-        );
-    }
-
-	return result;
-}
-
- -

This can be useful to reveal "hidden" properties (properties in the prototype chain which are not accessible through the object, because another property has the same name earlier in the prototype chain). Listing accessible properties only can easily be done by removing duplicates in the array.

- -

Creating new objects

- -

JavaScript has a number of predefined objects. In addition, you can create your own objects. You can create an object using an object initializer. Alternatively, you can first create a constructor function and then instantiate an object invoking that function in conjunction with the new operator.

- -

Using object initializers

- -

In addition to creating objects using a constructor function, you can create objects using an object initializer. Using object initializers is sometimes referred to as creating objects with literal notation. "Object initializer" is consistent with the terminology used by C++.

- -

The syntax for an object using an object initializer is:

- -
var obj = { property_1:   value_1,   // property_# may be an identifier...
-            2:            value_2,   // or a number...
-            // ...,
-            'property n': value_n }; // or a string
-
- -

where obj is the name of the new object, each property_i is an identifier (either a name, a number, or a string literal), and each value_i is an expression whose value is assigned to the property_i. The obj and assignment is optional; if you do not need to refer to this object elsewhere, you do not need to assign it to a variable. (Note that you may need to wrap the object literal in parentheses if the object appears where a statement is expected, so as not to have the literal be confused with a block statement.)

- -

Object initializers are expressions, and each object initializer results in a new object being created whenever the statement in which it appears is executed. Identical object initializers create distinct objects that will not compare to each other as equal. Objects are created as if a call to new Object() were made; that is, objects made from object literal expressions are instances of Object.

- -

The following statement creates an object and assigns it to the variable x if and only if the expression cond is true:

- -
if (cond) var x = {greeting: 'hi there'};
-
- -

The following example creates myHonda with three properties. Note that the engine property is also an object with its own properties.

- -
var myHonda = {color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}};
-
- -

You can also use object initializers to create arrays. See array literals.

- -

Using a constructor function

- -

Alternatively, you can create an object with these two steps:

- -
    -
  1. Define the object type by writing a constructor function. There is a strong convention, with good reason, to use a capital initial letter.
  2. -
  3. Create an instance of the object with new.
  4. -
- -

To define an object type, create a function for the object type that specifies its name, properties, and methods. For example, suppose you want to create an object type for cars. You want this type of object to be called Car, and you want it to have properties for make, model, and year. To do this, you would write the following function:

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

Notice the use of this to assign values to the object's properties based on the values passed to the function.

- -

Now you can create an object called mycar as follows:

- -
var mycar = new Car('Eagle', 'Talon TSi', 1993);
-
- -

This statement creates mycar and assigns it the specified values for its properties. Then the value of mycar.make is the string "Eagle", mycar.year is the integer 1993, and so on.

- -

You can create any number of Car objects by calls to new. For example,

- -
var kenscar = new Car('Nissan', '300ZX', 1992);
-var vpgscar = new Car('Mazda', 'Miata', 1990);
-
- -

An object can have a property that is itself another object. For example, suppose you define an object called person as follows:

- -
function Person(name, age, sex) {
-  this.name = name;
-  this.age = age;
-  this.sex = sex;
-}
-
- -

and then instantiate two new person objects as follows:

- -
var rand = new Person('Rand McKinnon', 33, 'M');
-var ken = new Person('Ken Jones', 39, 'M');
-
- -

Then, you can rewrite the definition of Car to include an owner property that takes a person object, as follows:

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

To instantiate the new objects, you then use the following:

- -
var car1 = new Car('Eagle', 'Talon TSi', 1993, rand);
-var car2 = new Car('Nissan', '300ZX', 1992, ken);
-
- -

Notice that instead of passing a literal string or integer value when creating the new objects, the above statements pass the objects rand and ken as the arguments for the owners. Then if you want to find out the name of the owner of car2, you can access the following property:

- -
car2.owner.name
-
- -

Note that you can always add a property to a previously defined object. For example, the statement

- -
car1.color = 'black';
-
- -

adds a property color to car1, and assigns it a value of "black." However, this does not affect any other objects. To add the new property to all objects of the same type, you have to add the property to the definition of the Car object type.

- -

Using the Object.create method

- -

Objects can also be created using the {{jsxref("Object.create()")}} method. This method can be very useful, because it allows you to choose the prototype object for the object you want to create, without having to define a constructor function.

- -
// Animal properties and method encapsulation
-var Animal = {
-  type: 'Invertebrates', // Default value of properties
-  displayType: function() {  // Method which will display type of Animal
-    console.log(this.type);
-  }
-};
-
-// Create new animal type called animal1
-var animal1 = Object.create(Animal);
-animal1.displayType(); // Output:Invertebrates
-
-// Create new animal type called Fishes
-var fish = Object.create(Animal);
-fish.type = 'Fishes';
-fish.displayType(); // Output:Fishes
- -

Inheritance

- -

All objects in JavaScript inherit from at least one other object. The object being inherited from is known as the prototype, and the inherited properties can be found in the prototype object of the constructor. See Inheritance and the prototype chain for more information.

- -

Indexing object properties

- -

You can refer to a property of an object either by its property name or by its ordinal index. If you initially define a property by its name, you must always refer to it by its name, and if you initially define a property by an index, you must always refer to it by its index.

- -

This restriction applies when you create an object and its properties with a constructor function (as we did previously with the Car object type) and when you define individual properties explicitly (for example, myCar.color = "red"). If you initially define an object property with an index, such as myCar[5] = "25 mpg", you subsequently refer to the property only as myCar[5].

- -

The exception to this rule is array-like object reflected from HTML, such as the forms array-like object. You can always refer to objects in these array-like objects by either their ordinal number (based on where they appear in the document) or their name (if defined). For example, if the second <FORM> tag in a document has a NAME attribute of "myForm", you can refer to the form as document.forms[1] or document.forms["myForm"] or document.forms.myForm.

- -

Defining properties for an object type

- -

You can add a property to a previously defined object type by using the prototype property. This defines a property that is shared by all objects of the specified type, rather than by just one instance of the object. The following code adds a color property to all objects of type Car, and then assigns a value to the color property of the object car1.

- -
Car.prototype.color = null;
-car1.color = 'black';
-
- -

See the prototype property of the Function object in the JavaScript reference for more information.

- -

Defining methods

- -

A method is a function associated with an object, or, simply put, a method is a property of an object that is a function. Methods are defined the way normal functions are defined, except that they have to be assigned as the property of an object. See also method definitions for more details. An example is:

- -
objectName.methodname = functionName;
-
-var myObj = {
-  myMethod: function(params) {
-    // ...do something
-  }
-
-  // OR THIS WORKS TOO
-
-  myOtherMethod(params) {
-    // ...do something else
-  }
-};
-
- -

where objectName is an existing object, methodname is the name you are assigning to the method, and functionName is the name of the function.

- -

You can then call the method in the context of the object as follows:

- -
object.methodname(params);
-
- -

You can define methods for an object type by including a method definition in the object constructor function. You could define a function that would format and display the properties of the previously-defined Car objects; for example,

- -
function displayCar() {
-  var result = `A Beautiful ${this.year} ${this.make} ${this.model}`;
-  pretty_print(result);
-}
-
- -

where pretty_print is a function to display a horizontal rule and a string. Notice the use of this to refer to the object to which the method belongs.

- -

You can make this function a method of Car by adding the statement

- -
this.displayCar = displayCar;
-
- -

to the object definition. So, the full definition of Car would now look like

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

Then you can call the displayCar method for each of the objects as follows:

- -
car1.displayCar();
-car2.displayCar();
-
- -

Using this for object references

- -

JavaScript has a special keyword, this, that you can use within a method to refer to the current object. For example, suppose you have 2 objects, Managerand Intern. Each object have their own nameage and job.  In the function sayHi(), notice there is this.name. When added to the 2 objects they can be called and returns the 'Hello, My name is' then adds the name value from that specific object. As shown below. 

- -
const Manager = {
-  name: "John",
-  age: 27,
-  job: "Software Engineer"
-}
-const Intern= {
-  name: "Ben",
-  age: 21,
-  job: "Software Engineer Intern"
-}
-
-function sayHi() {
-    console.log('Hello, my name is', this.name)
-}
-
-// add sayHi function to both objects
-Manager.sayHi = sayHi;
-Intern.sayHi = sayHi;
-
-Manager.sayHi() // Hello, my name is John'
-Intern.sayHi() // Hello, my name is Ben'
-
- -

The this refers to the object that it is in. You can create a new function called howOldAmI()which logs a sentence saying how old the person is. 

- -
function howOldAmI (){
-  console.log('I am ' + this.age + ' years old.')
-}
-Manager.howOldAmI = howOldAmI;
-Manager.howOldAmI() // I am 27 years old.
-
- -

Defining getters and setters

- -

A getter is a method that gets the value of a specific property. A setter is a method that sets the value of a specific property. You can define getters and setters on any predefined core object or user-defined object that supports the addition of new properties. The syntax for defining getters and setters uses the object literal syntax.

- -

The following illustrates how getters and setters could work for a user-defined object o.

- -
var o = {
-  a: 7,
-  get b() {
-    return this.a + 1;
-  },
-  set c(x) {
-    this.a = x / 2;
-  }
-};
-
-console.log(o.a); // 7
-console.log(o.b); // 8
-o.c = 50;
-console.log(o.a); // 25
-
- -

The o object's properties are:

- - - -

Please note that function names of getters and setters defined in an object literal using "[gs]et property()" (as opposed to __define[GS]etter__ ) are not the names of the getters themselves, even though the [gs]et propertyName(){ } syntax may mislead you to think otherwise. To name a function in a getter or setter using the "[gs]et property()" syntax, define an explicitly named function programmatically using {{jsxref("Object.defineProperty")}} (or the {{jsxref("Object.defineGetter", "Object.prototype.__defineGetter__")}} legacy fallback).

- -

The following code illustrates how getters and setters can extend the {{jsxref("Date")}} prototype to add a year property to all instances of the predefined Date class. It uses the Date class's existing getFullYear and setFullYear methods to support the year property's getter and setter.

- -

These statements define a getter and setter for the year property:

- -
var d = Date.prototype;
-Object.defineProperty(d, 'year', {
-  get: function() { return this.getFullYear(); },
-  set: function(y) { this.setFullYear(y); }
-});
-
- -

These statements use the getter and setter in a Date object:

- -
var now = new Date();
-console.log(now.year); // 2000
-now.year = 2001; // 987617605170
-console.log(now);
-// Wed Apr 18 11:13:25 GMT-0700 (Pacific Daylight Time) 2001
-
- -

In principle, getters and setters can be either

- - - -

When defining getters and setters using object initializers all you need to do is to prefix a getter method with get and a setter method with set. Of course, the getter method must not expect a parameter, while the setter method expects exactly one parameter (the new value to set). For instance:

- -
var o = {
-  a: 7,
-  get b() { return this.a + 1; },
-  set c(x) { this.a = x / 2; }
-};
-
- -

Getters and setters can also be added to an object at any time after creation using the Object.defineProperties method. This method's first parameter is the object on which you want to define the getter or setter. The second parameter is an object whose property names are the getter or setter names, and whose property values are objects for defining the getter or setter functions. Here's an example that defines the same getter and setter used in the previous example:

- -
var o = { a: 0 };
-
-Object.defineProperties(o, {
-    'b': { get: function() { return this.a + 1; } },
-    'c': { set: function(x) { this.a = x / 2; } }
-});
-
-o.c = 10; // Runs the setter, which assigns 10 / 2 (5) to the 'a' property
-console.log(o.b); // Runs the getter, which yields a + 1 or 6
-
- -

Which of the two forms to choose depends on your programming style and task at hand. If you already go for the object initializer when defining a prototype you will probably most of the time choose the first form. This form is more compact and natural. However, if you need to add getters and setters later — because you did not write the prototype or particular object — then the second form is the only possible form. The second form probably best represents the dynamic nature of JavaScript — but it can make the code hard to read and understand.

- -

Deleting properties

- -

You can remove a non-inherited property by using the delete operator. The following code shows how to remove a property.

- -
// Creates a new object, myobj, with two properties, a and b.
-var myobj = new Object;
-myobj.a = 5;
-myobj.b = 12;
-
-// Removes the a property, leaving myobj with only the b property.
-delete myobj.a;
-console.log ('a' in myobj); // output: "false"
-
- -

You can also use delete to delete a global variable if the var keyword was not used to declare the variable:

- -
g = 17;
-delete g;
-
- -

Comparing objects

- -

In JavaScript, objects are a reference type. Two distinct objects are never equal, even if they have the same properties. Only comparing the same object reference with itself yields true.

- -
// Two variables, two distinct objects with the same properties
-var fruit = {name: 'apple'};
-var fruitbear = {name: 'apple'};
-
-fruit == fruitbear; // return false
-fruit === fruitbear; // return false
- -
// Two variables, a single object
-var fruit = {name: 'apple'};
-var fruitbear = fruit;  // Assign fruit object reference to fruitbear
-
-// Here fruit and fruitbear are pointing to same object
-fruit == fruitbear; // return true
-fruit === fruitbear; // return true
-
-fruit.name = 'grape';
-console.log(fruitbear); // output: { name: "grape" }, instead of { name: "apple" }
-
- -

For more information about comparison operators, see Comparison operators.

- -

See also

- - - -

{{PreviousNext("Web/JavaScript/Guide/Regular_Expressions", "Web/JavaScript/Guide/Details_of_the_Object_Model")}}

diff --git a/files/tr/web/javascript/guide/working_with_objects/index.html b/files/tr/web/javascript/guide/working_with_objects/index.html new file mode 100644 index 0000000000..0782b4db6c --- /dev/null +++ b/files/tr/web/javascript/guide/working_with_objects/index.html @@ -0,0 +1,504 @@ +--- +title: Nesnelerle çalışmak +slug: Web/JavaScript/Guide/Nesneler_ile_çalışmak +translation_of: Web/JavaScript/Guide/Working_with_Objects +--- +
{{jsSidebar("JavaScript Rehberi")}} {{PreviousNext("Web/JavaScript/Guide/Keyed_collections", "Web/JavaScript/Guide/Details_of_the_Object_Model")}}
+ +

JavaScript basit bir nesne tabanlı paradigmada tasarlanmıştır. Bir nesne bir özellikler koleksiyonudur ve bir özellik bir ad (veya anahtar) ile bir değer arasındaki ilişkidir. Bir özelliğin değeri bir fonksiyon olabilir, bu durumda özellik bir metod olarak bilinir. Tarayıcıda önceden tanımlanmış olan nesnelere ek olarak, kendi nesnelerinizi de tanımlayabilirsiniz. Bu bölümde, nesnelerin, özelliklerin, fonksiyonların ve metodların nasıl kullanıldığı ve kendi nesnelerinizin nasıl oluşturulacağı açıklanmaktadır.

+ +

Nesnelere genel bakış

+ +

JavaScript'teki nesneler, diğer birçok programlama dilinde olduğu gibi, gerçek hayattaki nesnelerle karşılaştırılabilir. JavaScript'teki nesneler kavramı gerçek hayattaki somut nesnelerle anlaşılabilir.

+ +

JavaScript'te bir nesne, özellikleri ve tipiyle bağımsız bir varlıktır. Örneğin bir fincanla karşılaştırın. Bir fincan, özellikleri olan bir nesnedir. Bir fincan bir renge, bir tasarıma, ağırlığa, yapıldığı bir malzemeye vs. sahiptir. Aynı şekilde, JavaScript nesnelerinin de özelliklerini tanımlayan özellikleri olabilir.

+ +

Nesneler ve özellikleri

+ +

A JavaScript object has properties associated with it. A property of an object can be explained as a variable that is attached to the object. Object properties are basically the same as ordinary JavaScript variables, except for the attachment to objects. The properties of an object define the characteristics of the object. You access the properties of an object with a simple dot-notation:

+ +
objectName.propertyName
+
+ +

Like all JavaScript variables, both the object name (which could be a normal variable) and property name are case sensitive. You can define a property by assigning it a value. For example, let's create an object named myCar and give it properties named make, model, and year as follows:

+ +
var myCar = new Object();
+myCar.make = 'Ford';
+myCar.model = 'Mustang';
+myCar.year = 1969;
+
+ +

Unassigned properties of an object are {{jsxref("undefined")}} (and not {{jsxref("null")}}).

+ +
myCar.color; // undefined
+ +

Properties of JavaScript objects can also be accessed or set using a bracket notation (for more details see property accessors). Objects are sometimes called associative arrays, since each property is associated with a string value that can be used to access it. So, for example, you could access the properties of the myCar object as follows:

+ +
myCar['make'] = 'Ford';
+myCar['model'] = 'Mustang';
+myCar['year'] = 1969;
+
+ +

An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation. This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime). Examples are as follows:

+ +
// four variables are created and assigned in a single go,
+// separated by commas
+var myObj = new Object(),
+    str = 'myString',
+    rand = Math.random(),
+    obj = new Object();
+
+myObj.type              = 'Dot syntax';
+myObj['date created']   = 'String with space';
+myObj[str]              = 'String value';
+myObj[rand]             = 'Random Number';
+myObj[obj]              = 'Object';
+myObj['']               = 'Even an empty string';
+
+console.log(myObj);
+
+ +

Please note that all keys in the square bracket notation are converted to string unless they're Symbols, since JavaScript object property names (keys) can only be strings or Symbols (at some point, private names will also be added as the class fields proposal progresses, but you won't use them with [] form). For example, in the above code, when the key obj is added to the myObj, JavaScript will call the {{jsxref("Object.toString", "obj.toString()")}} method, and use this result string as the new key.

+ +

You can also access properties by using a string value that is stored in a variable:

+ +
var propertyName = 'make';
+myCar[propertyName] = 'Ford';
+
+propertyName = 'model';
+myCar[propertyName] = 'Mustang';
+
+ +

You can use the bracket notation with for...in to iterate over all the enumerable properties of an object. To illustrate how this works, the following function displays the properties of the object when you pass the object and the object's name as arguments to the function:

+ +
function showProps(obj, objName) {
+  var result = ``;
+  for (var i in obj) {
+    // obj.hasOwnProperty() is used to filter out properties from the object's prototype chain
+    if (obj.hasOwnProperty(i)) {
+      result += `${objName}.${i} = ${obj[i]}\n`;
+    }
+  }
+  return result;
+}
+
+ +

So, the function call showProps(myCar, "myCar") would return the following:

+ +
myCar.make = Ford
+myCar.model = Mustang
+myCar.year = 1969
+ +

Enumerate the properties of an object

+ +

Starting with ECMAScript 5, there are three native ways to list/traverse object properties:

+ + + +

Before ECMAScript 5, there was no native way to list all properties of an object. However, this can be achieved with the following function:

+ +
function listAllProperties(o) {
+	var objectToInspect;
+	var result = [];
+
+	for(objectToInspect = o; objectToInspect !== null;
+           objectToInspect = Object.getPrototypeOf(objectToInspect)) {
+        result = result.concat(
+            Object.getOwnPropertyNames(objectToInspect)
+        );
+    }
+
+	return result;
+}
+
+ +

This can be useful to reveal "hidden" properties (properties in the prototype chain which are not accessible through the object, because another property has the same name earlier in the prototype chain). Listing accessible properties only can easily be done by removing duplicates in the array.

+ +

Creating new objects

+ +

JavaScript has a number of predefined objects. In addition, you can create your own objects. You can create an object using an object initializer. Alternatively, you can first create a constructor function and then instantiate an object invoking that function in conjunction with the new operator.

+ +

Using object initializers

+ +

In addition to creating objects using a constructor function, you can create objects using an object initializer. Using object initializers is sometimes referred to as creating objects with literal notation. "Object initializer" is consistent with the terminology used by C++.

+ +

The syntax for an object using an object initializer is:

+ +
var obj = { property_1:   value_1,   // property_# may be an identifier...
+            2:            value_2,   // or a number...
+            // ...,
+            'property n': value_n }; // or a string
+
+ +

where obj is the name of the new object, each property_i is an identifier (either a name, a number, or a string literal), and each value_i is an expression whose value is assigned to the property_i. The obj and assignment is optional; if you do not need to refer to this object elsewhere, you do not need to assign it to a variable. (Note that you may need to wrap the object literal in parentheses if the object appears where a statement is expected, so as not to have the literal be confused with a block statement.)

+ +

Object initializers are expressions, and each object initializer results in a new object being created whenever the statement in which it appears is executed. Identical object initializers create distinct objects that will not compare to each other as equal. Objects are created as if a call to new Object() were made; that is, objects made from object literal expressions are instances of Object.

+ +

The following statement creates an object and assigns it to the variable x if and only if the expression cond is true:

+ +
if (cond) var x = {greeting: 'hi there'};
+
+ +

The following example creates myHonda with three properties. Note that the engine property is also an object with its own properties.

+ +
var myHonda = {color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}};
+
+ +

You can also use object initializers to create arrays. See array literals.

+ +

Using a constructor function

+ +

Alternatively, you can create an object with these two steps:

+ +
    +
  1. Define the object type by writing a constructor function. There is a strong convention, with good reason, to use a capital initial letter.
  2. +
  3. Create an instance of the object with new.
  4. +
+ +

To define an object type, create a function for the object type that specifies its name, properties, and methods. For example, suppose you want to create an object type for cars. You want this type of object to be called Car, and you want it to have properties for make, model, and year. To do this, you would write the following function:

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

Notice the use of this to assign values to the object's properties based on the values passed to the function.

+ +

Now you can create an object called mycar as follows:

+ +
var mycar = new Car('Eagle', 'Talon TSi', 1993);
+
+ +

This statement creates mycar and assigns it the specified values for its properties. Then the value of mycar.make is the string "Eagle", mycar.year is the integer 1993, and so on.

+ +

You can create any number of Car objects by calls to new. For example,

+ +
var kenscar = new Car('Nissan', '300ZX', 1992);
+var vpgscar = new Car('Mazda', 'Miata', 1990);
+
+ +

An object can have a property that is itself another object. For example, suppose you define an object called person as follows:

+ +
function Person(name, age, sex) {
+  this.name = name;
+  this.age = age;
+  this.sex = sex;
+}
+
+ +

and then instantiate two new person objects as follows:

+ +
var rand = new Person('Rand McKinnon', 33, 'M');
+var ken = new Person('Ken Jones', 39, 'M');
+
+ +

Then, you can rewrite the definition of Car to include an owner property that takes a person object, as follows:

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

To instantiate the new objects, you then use the following:

+ +
var car1 = new Car('Eagle', 'Talon TSi', 1993, rand);
+var car2 = new Car('Nissan', '300ZX', 1992, ken);
+
+ +

Notice that instead of passing a literal string or integer value when creating the new objects, the above statements pass the objects rand and ken as the arguments for the owners. Then if you want to find out the name of the owner of car2, you can access the following property:

+ +
car2.owner.name
+
+ +

Note that you can always add a property to a previously defined object. For example, the statement

+ +
car1.color = 'black';
+
+ +

adds a property color to car1, and assigns it a value of "black." However, this does not affect any other objects. To add the new property to all objects of the same type, you have to add the property to the definition of the Car object type.

+ +

Using the Object.create method

+ +

Objects can also be created using the {{jsxref("Object.create()")}} method. This method can be very useful, because it allows you to choose the prototype object for the object you want to create, without having to define a constructor function.

+ +
// Animal properties and method encapsulation
+var Animal = {
+  type: 'Invertebrates', // Default value of properties
+  displayType: function() {  // Method which will display type of Animal
+    console.log(this.type);
+  }
+};
+
+// Create new animal type called animal1
+var animal1 = Object.create(Animal);
+animal1.displayType(); // Output:Invertebrates
+
+// Create new animal type called Fishes
+var fish = Object.create(Animal);
+fish.type = 'Fishes';
+fish.displayType(); // Output:Fishes
+ +

Inheritance

+ +

All objects in JavaScript inherit from at least one other object. The object being inherited from is known as the prototype, and the inherited properties can be found in the prototype object of the constructor. See Inheritance and the prototype chain for more information.

+ +

Indexing object properties

+ +

You can refer to a property of an object either by its property name or by its ordinal index. If you initially define a property by its name, you must always refer to it by its name, and if you initially define a property by an index, you must always refer to it by its index.

+ +

This restriction applies when you create an object and its properties with a constructor function (as we did previously with the Car object type) and when you define individual properties explicitly (for example, myCar.color = "red"). If you initially define an object property with an index, such as myCar[5] = "25 mpg", you subsequently refer to the property only as myCar[5].

+ +

The exception to this rule is array-like object reflected from HTML, such as the forms array-like object. You can always refer to objects in these array-like objects by either their ordinal number (based on where they appear in the document) or their name (if defined). For example, if the second <FORM> tag in a document has a NAME attribute of "myForm", you can refer to the form as document.forms[1] or document.forms["myForm"] or document.forms.myForm.

+ +

Defining properties for an object type

+ +

You can add a property to a previously defined object type by using the prototype property. This defines a property that is shared by all objects of the specified type, rather than by just one instance of the object. The following code adds a color property to all objects of type Car, and then assigns a value to the color property of the object car1.

+ +
Car.prototype.color = null;
+car1.color = 'black';
+
+ +

See the prototype property of the Function object in the JavaScript reference for more information.

+ +

Defining methods

+ +

A method is a function associated with an object, or, simply put, a method is a property of an object that is a function. Methods are defined the way normal functions are defined, except that they have to be assigned as the property of an object. See also method definitions for more details. An example is:

+ +
objectName.methodname = functionName;
+
+var myObj = {
+  myMethod: function(params) {
+    // ...do something
+  }
+
+  // OR THIS WORKS TOO
+
+  myOtherMethod(params) {
+    // ...do something else
+  }
+};
+
+ +

where objectName is an existing object, methodname is the name you are assigning to the method, and functionName is the name of the function.

+ +

You can then call the method in the context of the object as follows:

+ +
object.methodname(params);
+
+ +

You can define methods for an object type by including a method definition in the object constructor function. You could define a function that would format and display the properties of the previously-defined Car objects; for example,

+ +
function displayCar() {
+  var result = `A Beautiful ${this.year} ${this.make} ${this.model}`;
+  pretty_print(result);
+}
+
+ +

where pretty_print is a function to display a horizontal rule and a string. Notice the use of this to refer to the object to which the method belongs.

+ +

You can make this function a method of Car by adding the statement

+ +
this.displayCar = displayCar;
+
+ +

to the object definition. So, the full definition of Car would now look like

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

Then you can call the displayCar method for each of the objects as follows:

+ +
car1.displayCar();
+car2.displayCar();
+
+ +

Using this for object references

+ +

JavaScript has a special keyword, this, that you can use within a method to refer to the current object. For example, suppose you have 2 objects, Managerand Intern. Each object have their own nameage and job.  In the function sayHi(), notice there is this.name. When added to the 2 objects they can be called and returns the 'Hello, My name is' then adds the name value from that specific object. As shown below. 

+ +
const Manager = {
+  name: "John",
+  age: 27,
+  job: "Software Engineer"
+}
+const Intern= {
+  name: "Ben",
+  age: 21,
+  job: "Software Engineer Intern"
+}
+
+function sayHi() {
+    console.log('Hello, my name is', this.name)
+}
+
+// add sayHi function to both objects
+Manager.sayHi = sayHi;
+Intern.sayHi = sayHi;
+
+Manager.sayHi() // Hello, my name is John'
+Intern.sayHi() // Hello, my name is Ben'
+
+ +

The this refers to the object that it is in. You can create a new function called howOldAmI()which logs a sentence saying how old the person is. 

+ +
function howOldAmI (){
+  console.log('I am ' + this.age + ' years old.')
+}
+Manager.howOldAmI = howOldAmI;
+Manager.howOldAmI() // I am 27 years old.
+
+ +

Defining getters and setters

+ +

A getter is a method that gets the value of a specific property. A setter is a method that sets the value of a specific property. You can define getters and setters on any predefined core object or user-defined object that supports the addition of new properties. The syntax for defining getters and setters uses the object literal syntax.

+ +

The following illustrates how getters and setters could work for a user-defined object o.

+ +
var o = {
+  a: 7,
+  get b() {
+    return this.a + 1;
+  },
+  set c(x) {
+    this.a = x / 2;
+  }
+};
+
+console.log(o.a); // 7
+console.log(o.b); // 8
+o.c = 50;
+console.log(o.a); // 25
+
+ +

The o object's properties are:

+ + + +

Please note that function names of getters and setters defined in an object literal using "[gs]et property()" (as opposed to __define[GS]etter__ ) are not the names of the getters themselves, even though the [gs]et propertyName(){ } syntax may mislead you to think otherwise. To name a function in a getter or setter using the "[gs]et property()" syntax, define an explicitly named function programmatically using {{jsxref("Object.defineProperty")}} (or the {{jsxref("Object.defineGetter", "Object.prototype.__defineGetter__")}} legacy fallback).

+ +

The following code illustrates how getters and setters can extend the {{jsxref("Date")}} prototype to add a year property to all instances of the predefined Date class. It uses the Date class's existing getFullYear and setFullYear methods to support the year property's getter and setter.

+ +

These statements define a getter and setter for the year property:

+ +
var d = Date.prototype;
+Object.defineProperty(d, 'year', {
+  get: function() { return this.getFullYear(); },
+  set: function(y) { this.setFullYear(y); }
+});
+
+ +

These statements use the getter and setter in a Date object:

+ +
var now = new Date();
+console.log(now.year); // 2000
+now.year = 2001; // 987617605170
+console.log(now);
+// Wed Apr 18 11:13:25 GMT-0700 (Pacific Daylight Time) 2001
+
+ +

In principle, getters and setters can be either

+ + + +

When defining getters and setters using object initializers all you need to do is to prefix a getter method with get and a setter method with set. Of course, the getter method must not expect a parameter, while the setter method expects exactly one parameter (the new value to set). For instance:

+ +
var o = {
+  a: 7,
+  get b() { return this.a + 1; },
+  set c(x) { this.a = x / 2; }
+};
+
+ +

Getters and setters can also be added to an object at any time after creation using the Object.defineProperties method. This method's first parameter is the object on which you want to define the getter or setter. The second parameter is an object whose property names are the getter or setter names, and whose property values are objects for defining the getter or setter functions. Here's an example that defines the same getter and setter used in the previous example:

+ +
var o = { a: 0 };
+
+Object.defineProperties(o, {
+    'b': { get: function() { return this.a + 1; } },
+    'c': { set: function(x) { this.a = x / 2; } }
+});
+
+o.c = 10; // Runs the setter, which assigns 10 / 2 (5) to the 'a' property
+console.log(o.b); // Runs the getter, which yields a + 1 or 6
+
+ +

Which of the two forms to choose depends on your programming style and task at hand. If you already go for the object initializer when defining a prototype you will probably most of the time choose the first form. This form is more compact and natural. However, if you need to add getters and setters later — because you did not write the prototype or particular object — then the second form is the only possible form. The second form probably best represents the dynamic nature of JavaScript — but it can make the code hard to read and understand.

+ +

Deleting properties

+ +

You can remove a non-inherited property by using the delete operator. The following code shows how to remove a property.

+ +
// Creates a new object, myobj, with two properties, a and b.
+var myobj = new Object;
+myobj.a = 5;
+myobj.b = 12;
+
+// Removes the a property, leaving myobj with only the b property.
+delete myobj.a;
+console.log ('a' in myobj); // output: "false"
+
+ +

You can also use delete to delete a global variable if the var keyword was not used to declare the variable:

+ +
g = 17;
+delete g;
+
+ +

Comparing objects

+ +

In JavaScript, objects are a reference type. Two distinct objects are never equal, even if they have the same properties. Only comparing the same object reference with itself yields true.

+ +
// Two variables, two distinct objects with the same properties
+var fruit = {name: 'apple'};
+var fruitbear = {name: 'apple'};
+
+fruit == fruitbear; // return false
+fruit === fruitbear; // return false
+ +
// Two variables, a single object
+var fruit = {name: 'apple'};
+var fruitbear = fruit;  // Assign fruit object reference to fruitbear
+
+// Here fruit and fruitbear are pointing to same object
+fruit == fruitbear; // return true
+fruit === fruitbear; // return true
+
+fruit.name = 'grape';
+console.log(fruitbear); // output: { name: "grape" }, instead of { name: "apple" }
+
+ +

For more information about comparison operators, see Comparison operators.

+ +

See also

+ + + +

{{PreviousNext("Web/JavaScript/Guide/Regular_Expressions", "Web/JavaScript/Guide/Details_of_the_Object_Model")}}

-- cgit v1.2.3-54-g00ecf