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 --- files/tr/web/javascript/data_structures/index.html | 298 ++++++++++ .../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 ++++++++++++++++ .../global_objects/array/prototype/index.html | 205 ------- .../global_objects/boolean/prototype/index.html | 77 --- .../global_objects/map/prototype/index.html | 85 --- .../reference/operators/function_star_/index.html | 84 +++ .../web/javascript/reference/operators/index.html | 277 +++++++++ .../reference/operators/instanceof/index.html | 207 +++++++ .../reference/operators/super/index.html | 165 +++++ .../javascript/reference/operators/this/index.html | 347 +++++++++++ .../reference/operators/typeof/index.html | 259 ++++++++ .../arithmetic_operators/index.html" | 294 --------- .../bitwise_operators/index.html" | 565 ------------------ .../operat\303\266rler/function_star_/index.html" | 84 --- .../reference/operat\303\266rler/index.html" | 277 --------- .../operat\303\266rler/instanceof/index.html" | 207 ------- .../mantiksal_operatorler/index.html" | 312 ---------- .../reference/operat\303\266rler/super/index.html" | 165 ----- .../reference/operat\303\266rler/this/index.html" | 347 ----------- .../operat\303\266rler/typeof/index.html" | 259 -------- .../veri_yap\304\261s\304\261/index.html" | 298 ---------- 26 files changed, 3222 insertions(+), 4760 deletions(-) create mode 100644 files/tr/web/javascript/data_structures/index.html 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 delete mode 100644 files/tr/web/javascript/reference/global_objects/array/prototype/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/boolean/prototype/index.html delete mode 100644 files/tr/web/javascript/reference/global_objects/map/prototype/index.html create mode 100644 files/tr/web/javascript/reference/operators/function_star_/index.html create mode 100644 files/tr/web/javascript/reference/operators/index.html create mode 100644 files/tr/web/javascript/reference/operators/instanceof/index.html create mode 100644 files/tr/web/javascript/reference/operators/super/index.html create mode 100644 files/tr/web/javascript/reference/operators/this/index.html create mode 100644 files/tr/web/javascript/reference/operators/typeof/index.html delete mode 100644 "files/tr/web/javascript/reference/operat\303\266rler/arithmetic_operators/index.html" delete mode 100644 "files/tr/web/javascript/reference/operat\303\266rler/bitwise_operators/index.html" delete mode 100644 "files/tr/web/javascript/reference/operat\303\266rler/function_star_/index.html" delete mode 100644 "files/tr/web/javascript/reference/operat\303\266rler/index.html" delete mode 100644 "files/tr/web/javascript/reference/operat\303\266rler/instanceof/index.html" delete mode 100644 "files/tr/web/javascript/reference/operat\303\266rler/mantiksal_operatorler/index.html" delete mode 100644 "files/tr/web/javascript/reference/operat\303\266rler/super/index.html" delete mode 100644 "files/tr/web/javascript/reference/operat\303\266rler/this/index.html" delete mode 100644 "files/tr/web/javascript/reference/operat\303\266rler/typeof/index.html" delete mode 100644 "files/tr/web/javascript/veri_yap\304\261s\304\261/index.html" (limited to 'files/tr/web/javascript') diff --git a/files/tr/web/javascript/data_structures/index.html b/files/tr/web/javascript/data_structures/index.html new file mode 100644 index 0000000000..693d18233a --- /dev/null +++ b/files/tr/web/javascript/data_structures/index.html @@ -0,0 +1,298 @@ +--- +title: JavaScript veri tipi ve veri yapısı +slug: Web/JavaScript/Veri_Yapısı +tags: + - Başlangıç + - JavaScript + - Veri Türleri +translation_of: Web/JavaScript/Data_structures +--- +
{{jsSidebar("More")}}
+ +

Programlama dilleri dil ile birlikte gelen sabit veri yapılarına sahiptir, fakat bu veri yapıları dilden dile değişiklik gösterir. Bu makale JavaScript'teki sabit veri yapılarını ve bu veri yapılarının özelliklerini listeler; böylece bu veri yapıları kullanılarak farklı veri yapıları yaratılabilir. Makale boyunca karşılaştırmanın mümkün olduğu bölümlerde, farklı dillerle kıyaslama yapılmıştır.

+ +

Dinamik Veri Tipi

+ +

JavaScript esnek (ya da dinamik) veri tipine sahip bir dildir. JavaScript dilinde değişkenler belirli bir veri tipi ile direkt ve sabit olarak ilişkilendirilmez ve herhangi bir değişkene herhangi bir veri tipine sahip bir değer atanabilir, bu değer daha sonra farklı bir veri tipinin değeri ile değiştirilebilir.

+ +
var foo = 42;    // foo değişkeni şuan bir sayıdır
+foo     = 'bar'; // foo değişkeni şuan karakter dizisidir
+foo     = true;  // foo değişkeni şuan boolean veri türüdür
+
+ +

Veri Tipleri

+ +

Son ECMAScript standartları 7 veri tipi tanımlar:

+ + + +

İlkel (Primitive)  değerler

+ +

Nesne dışındaki bütün veri tipleri sonradan değiştirilemez değerler tanımlar. Örnek olarak C dilinin tersine karakter dizileri (String) değiştirilemez. Bu tipteki değerler ilkel değerler (primitive values) olarak tanımlanır.

+ +

Boolean tipi

+ +

Boolean veri tipi doğru ( true ) ve yanlış ( false ) olmak üzere iki mantıksal değerden birine sahip olan veri tiplerini temsil eder.

+ +

Null tipi

+ +

Boş olan değişkenlerin alabiileceği tek değer vardır: null. Daha fazla detay için buraya bakınız {{jsxref("null")}} and {{Glossary("Null")}}.

+ +

Undefined tipi

+ +

Herhangi bir değer atanmamış değişkenlerin değeri undefined (tanımlanmamış)dır. Daha fazla detay için buraya {{jsxref("undefined")}}  ve buraya {{Glossary("Undefined")}} bakınız.

+ +

Number type

+ +

According to the ECMAScript standard, there is only one number type: the double-precision 64-bit binary format IEEE 754 value (numbers between -(253 -1) and 253 -1). There is no specific type for integers. In addition to being able to represent floating-point numbers, the number type has three symbolic values: +Infinity, -Infinity, and NaN (not-a-number).

+ +

To check for the largest available value or smallest available value within +/-Infinity, you can use the constants {{jsxref("Number.MAX_VALUE")}} or {{jsxref("Number.MIN_VALUE")}} and starting with ECMAScript 2015, you are also able to check if a number is in the double-precision floating-point number range using {{jsxref("Number.isSafeInteger()")}} as well as {{jsxref("Number.MAX_SAFE_INTEGER")}} and {{jsxref("Number.MIN_SAFE_INTEGER")}}. Beyond this range, integers in JavaScript are not safe anymore and will be a double-precision floating point approximation of the value.

+ +

The number type has only one integer that has two representations: 0 is represented as -0 and +0. ("0" is an alias for +0). In the praxis, this has almost no impact. For example +0 === -0 is true. However, you are able to notice this when you divide by zero:

+ +
> 42 / +0
+Infinity
+> 42 / -0
+-Infinity
+
+ +

Although a number often represents only its value, JavaScript provides some binary operators. These can be used to represent several Boolean values within a single number using bit masking. However, this is usually considered a bad practice, since JavaScript offers other means to represent a set of Booleans (like an array of Booleans or an object with Boolean values assigned to named properties). Bit masking also tends to make the code more difficult to read, understand, and maintain. It may be necessary to use such techniques in very constrained environments, like when trying to cope with the storage limitation of local storage or in extreme cases when each bit over the network counts. This technique should only be considered when it is the last measure that can be taken to optimize size.

+ +

String type

+ +

JavaScript's {{jsxref("Global_Objects/String", "String")}} type is used to represent textual data. It is a set of "elements" of 16-bit unsigned integer values. Each element in the String occupies a position in the String. The first element is at index 0, the next at index 1, and so on. The length of a String is the number of elements in it.

+ +

Unlike in languages like C, JavaScript strings are immutable. This means that once a string is created, it is not possible to modify it. However, it is still possible to create another string based on an operation on the original string. For example:

+ + + +

Beware of "stringly-typing" your code!

+ +

It can be tempting to use strings to represent complex data. Doing this comes with short-term benefits:

+ + + +

With conventions, it is possible to represent any data structure in a string. This does not make it a good idea. For instance, with a separator, one could emulate a list (while a JavaScript array would be more suitable). Unfortunately, when the separator is used in one of the "list" elements, then, the list is broken. An escape character can be chosen, etc. All of this requires conventions and creates an unnecessary maintenance burden.

+ +

Use strings for textual data. When representing complex data, parse strings and use the appropriate abstraction.

+ +

Symbol type

+ +

Symbols are new to JavaScript in ECMAScript 2015. A Symbol is a unique and immutable primitive value and may be used as the key of an Object property (see below). In some programming languages, Symbols are called atoms. For more details see {{Glossary("Symbol")}} and the {{jsxref("Symbol")}} object wrapper in JavaScript.

+ +

Objects

+ +

In computer science, an object is a value in memory which is possibly referenced by an {{Glossary("Identifier", "identifier")}}.

+ +

Properties

+ +

In JavaScript, objects can be seen as a collection of properties. With the object literal syntax, a limited set of properties are initialized; then properties can be added and removed. Property values can be values of any type, including other objects, which enables building complex data structures. Properties are identified using key values. A key value is either a String or a Symbol value.

+ +

There are two types of object properties which have certain attributes: The data property and the accessor property.

+ +

Data property

+ +

Associates a key with a value and has the following attributes:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Attributes of a data property
AttributeTypeDescriptionDefault value
[[Value]]Any JavaScript typeThe value retrieved by a get access of the property.undefined
[[Writable]]BooleanIf false, the property's [[Value]] can't be changed.false
[[Enumerable]]BooleanIf true, the property will be enumerated in for...in loops. See also Enumerability and ownership of propertiesfalse
[[Configurable]]BooleanIf false, the property can't be deleted, can't be changed to an accessor property and attributes other than [[Value]] and [[Writable]] can't be changed.false
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Obsolete attributes (as of ECMAScript 3, renamed in ECMAScript 5)
AttributeTypeDescription
Read-onlyBooleanReversed state of the ES5 [[Writable]] attribute.
DontEnumBooleanReversed state of the ES5 [[Enumerable]] attribute.
DontDeleteBooleanReversed state of the ES5 [[Configurable]] attribute.
+ +

Accessor property

+ +

Associates a key with one or two accessor functions (get and set) to retrieve or store a value and has the following attributes:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Attributes of an accessor property
AttributeTypeDescriptionDefault value
[[Get]]Function object or undefinedThe function is called with an empty argument list and retrieves the property value whenever a get access to the value is performed. See also get.undefined
[[Set]]Function object or undefinedThe function is called with an argument that contains the assigned value and is executed whenever a specified property is attempted to be changed. See also set.undefined
[[Enumerable]]BooleanIf true, the property will be enumerated in for...in loops.false
[[Configurable]]BooleanIf false, the property can't be deleted and can't be changed to a data property.false
+ +
+

Note: Attribute is usually used by JavaScript engine, so you can't directly access it (see more about Object.defineProperty()). That's why the attribute is put in double square brackets instead of single.

+
+ +

"Normal" objects, and functions

+ +

A JavaScript object is a mapping between keys and values. Keys are strings (or {{jsxref("Symbol")}}s) and values can be anything. This makes objects a natural fit for hashmaps.

+ +

Functions are regular objects with the additional capability of being callable.

+ +

Dates

+ +

When representing dates, the best choice is to use the built-in Date utility in JavaScript.

+ +

Indexed collections: Arrays and typed Arrays

+ +

Arrays are regular objects for which there is a particular relationship between integer-key-ed properties and the 'length' property. Additionally, arrays inherit from Array.prototype which provides to them a handful of convenient methods to manipulate arrays. For example, indexOf (searching a value in the array) or push (adding an element to the array), etc. This makes Arrays a perfect candidate to represent lists or sets.

+ +

Typed Arrays are new to JavaScript with ECMAScript 2015 and present an array-like view of an underlying binary data buffer. The following table helps you to find the equivalent C data types:

+ +

{{page("/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray", "TypedArray_objects", "", 0, 3)}}

+ +

Keyed collections: Maps, Sets, WeakMaps, WeakSets

+ +

These data structures take object references as keys and are introduced in ECMAScript Edition 6. {{jsxref("Set")}} and {{jsxref("WeakSet")}} represent a set of objects, while {{jsxref("Map")}} and {{jsxref("WeakMap")}} associate a value to an object. The difference between Maps and WeakMaps is that in the former, object keys can be enumerated over. This allows garbage collection optimizations in the latter case.

+ +

One could implement Maps and Sets in pure ECMAScript 5. However, since objects cannot be compared (in the sense of "less than" for instance), look-up performance would necessarily be linear. Native implementations of them (including WeakMaps) can have look-up performance that is approximately logarithmic to constant time.

+ +

Usually, to bind data to a DOM node, one could set properties directly on the object or use data-* attributes. This has the downside that the data is available to any script running in the same context. Maps and WeakMaps make it easy to privately bind data to an object.

+ +

Structured data: JSON

+ +

JSON (JavaScript Object Notation) is a lightweight data-interchange format, derived from JavaScript but used by many programming languages. JSON builds universal data structures. See {{Glossary("JSON")}} and {{jsxref("JSON")}} for more details.

+ +

More objects in the standard library

+ +

JavaScript has a standard library of built-in objects. Please have a look at the reference to find out about more objects.

+ +

Determining types using the typeof operator

+ +

The typeof operator can help you to find the type of your variable. Please read the reference page for more details and edge cases.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-8', 'Types')}}{{Spec2('ES5.1')}}
{{SpecName('ES2015', '#sec-ecmascript-data-types-and-values', 'ECMAScript Data Types and Values')}}{{Spec2('ES2015')}}Added Symbol.
{{SpecName('ESDraft', '#sec-ecmascript-data-types-and-values', 'ECMAScript Data Types and Values')}}{{Spec2('ESDraft')}}
+ +

See also

+ + 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")}}

diff --git a/files/tr/web/javascript/reference/global_objects/array/prototype/index.html b/files/tr/web/javascript/reference/global_objects/array/prototype/index.html deleted file mode 100644 index 19ffe3c80f..0000000000 --- a/files/tr/web/javascript/reference/global_objects/array/prototype/index.html +++ /dev/null @@ -1,205 +0,0 @@ ---- -title: Array.prototype -slug: Web/JavaScript/Reference/Global_Objects/Array/prototype -translation_of: Web/JavaScript/Reference/Global_Objects/Array/prototype ---- -
{{JSRef("Global_Objects", "Array")}}
- -

Summary

- -

The Array.prototype property represents the prototype for the {{jsxref("Global_Objects/Array", "Array")}} constructor.

- -
{{js_property_attributes(0, 0, 0)}}
- -

Description

- -

{{jsxref("Global_Objects/Array", "Array")}} instances inherit from Array.prototype. As with all constructors, you can change the constructor's prototype object to make changes to all {{jsxref("Global_Objects/Array", "Array")}} instances.

- -

Little known fact: Array.prototype itself is an {{jsxref("Global_Objects/Array", "Array")}}:

- -
Array.isArray(Array.prototype); // true
-
- -

Properties

- -
-
Array.prototype.constructor
-
Specifies the function that creates an object's prototype.
-
{{jsxref("Array.prototype.length")}}
-
Reflects the number of elements in an array.
-
- -

Methods

- -

Mutator methods

- -

These methods modify the array:

- -
-
{{jsxref("Array.prototype.copyWithin()")}} {{experimental_inline}}
-
Copies a sequence of array elements within the array.
-
{{jsxref("Array.prototype.fill()")}} {{experimental_inline}}
-
Fills all the elements of an array from a start index to an end index with a static value.
-
{{jsxref("Array.prototype.pop()")}}
-
Removes the last element from an array and returns that element.
-
{{jsxref("Array.prototype.push()")}}
-
Adds one or more elements to the end of an array and returns the new length of the array.
-
{{jsxref("Array.prototype.reverse()")}}
-
Reverses the order of the elements of an array in place — the first becomes the last, and the last becomes the first.
-
{{jsxref("Array.prototype.shift()")}}
-
Removes the first element from an array and returns that element.
-
{{jsxref("Array.prototype.sort()")}}
-
Sorts the elements of an array in place and returns the array.
-
{{jsxref("Array.prototype.splice()")}}
-
Adds and/or removes elements from an array.
-
{{jsxref("Array.prototype.unshift()")}}
-
Adds one or more elements to the front of an array and returns the new length of the array.
-
- -

Accessor methods

- -

These methods do not modify the array and return some representation of the array.

- -
-
{{jsxref("Array.prototype.concat()")}}
-
Returns a new array comprised of this array joined with other array(s) and/or value(s).
-
{{jsxref("Array.prototype.includes()")}} {{experimental_inline}}
-
Determines whether an array contains a certain element, returning true or false as appropriate.
-
{{jsxref("Array.prototype.join()")}}
-
Joins all elements of an array into a string.
-
{{jsxref("Array.prototype.slice()")}}
-
Extracts a section of an array and returns a new array.
-
{{jsxref("Array.prototype.toSource()")}} {{non-standard_inline}}
-
Returns an array literal representing the specified array; you can use this value to create a new array. Overrides the {{jsxref("Object.prototype.toSource()")}} method.
-
{{jsxref("Array.prototype.toString()")}}
-
Returns a string representing the array and its elements. Overrides the {{jsxref("Object.prototype.toString()")}} method.
-
{{jsxref("Array.prototype.toLocaleString()")}}
-
Returns a localized string representing the array and its elements. Overrides the {{jsxref("Object.prototype.toLocaleString()")}} method.
-
{{jsxref("Array.prototype.indexOf()")}}
-
Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.
-
{{jsxref("Array.prototype.lastIndexOf()")}}
-
Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.
-
- -

Iteration methods

- -

Several methods take as arguments functions to be called back while processing the array. When these methods are called, the length of the array is sampled, and any element added beyond this length from within the callback is not visited. Other changes to the array (setting the value of or deleting an element) may affect the results of the operation if the method visits the changed element afterwards. While the specific behavior of these methods in such cases is well-defined, you should not rely upon it so as not to confuse others who might read your code. If you must mutate the array, copy into a new array instead.

- -
-
{{jsxref("Array.prototype.forEach()")}}
-
Calls a function for each element in the array.
-
{{jsxref("Array.prototype.entries()")}} {{experimental_inline}}
-
Returns a new Array Iterator object that contains the key/value pairs for each index in the array.
-
{{jsxref("Array.prototype.every()")}}
-
Returns true if every element in this array satisfies the provided testing function.
-
{{jsxref("Array.prototype.some()")}}
-
Returns true if at least one element in this array satisfies the provided testing function.
-
{{jsxref("Array.prototype.filter()")}}
-
Creates a new array with all of the elements of this array for which the provided filtering function returns true.
-
{{jsxref("Array.prototype.find()")}} {{experimental_inline}}
-
Returns the found value in the array, if an element in the array satisfies the provided testing function or undefined if not found.
-
{{jsxref("Array.prototype.findIndex()")}} {{experimental_inline}}
-
Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found.
-
{{jsxref("Array.prototype.keys()")}} {{experimental_inline}}
-
Returns a new Array Iterator that contains the keys for each index in the array.
-
{{jsxref("Array.prototype.map()")}}
-
Creates a new array with the results of calling a provided function on every element in this array.
-
{{jsxref("Array.prototype.reduce()")}}
-
Apply a function against an accumulator and each value of the array (from left-to-right) as to reduce it to a single value.
-
{{jsxref("Array.prototype.reduceRight()")}}
-
Apply a function against an accumulator and each value of the array (from right-to-left) as to reduce it to a single value.
-
{{jsxref("Array.prototype.values()")}} {{experimental_inline}}
-
Returns a new Array Iterator object that contains the values for each index in the array.
-
{{jsxref("Array.prototype.@@iterator()", "Array.prototype[@@iterator]()")}} {{experimental_inline}}
-
Returns a new Array Iterator object that contains the values for each index in the array.
-
- -

Generic methods

- -

Many methods on the JavaScript Array object are designed to be generally applied to all objects which “look like” Arrays. That is, they can be used on any object which has a length property, and which can usefully be accessed using numeric property names (as with array[5] indexing). TODO: give examples with Array.prototype.forEach.call, and adding the method to an object like {{jsxref("Global_Objects/JavaArray", "JavaArray")}} or {{jsxref("Global_Objects/String", "String")}}. Some methods, such as {{jsxref("Array.join", "join")}}, only read the length and numeric properties of the object they are called on. Others, like {{jsxref("Array.reverse", "reverse")}}, require that the object's numeric properties and length be mutable; these methods can therefore not be called on objects like {{jsxref("Global_Objects/String", "String")}}, which does not permit its length property or synthesized numeric properties to be set.

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
ECMAScript 1st Edition.StandardInitial definition.
{{SpecName('ES5.1', '#sec-15.4.3.1', 'Array.prototype')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype', 'Array.prototype')}}{{Spec2('ES6')}} 
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

See also

- - diff --git a/files/tr/web/javascript/reference/global_objects/boolean/prototype/index.html b/files/tr/web/javascript/reference/global_objects/boolean/prototype/index.html deleted file mode 100644 index dcb92f48b3..0000000000 --- a/files/tr/web/javascript/reference/global_objects/boolean/prototype/index.html +++ /dev/null @@ -1,77 +0,0 @@ ---- -title: Boolean.prototype -slug: Web/JavaScript/Reference/Global_Objects/Boolean/prototype -translation_of: Web/JavaScript/Reference/Global_Objects/Boolean -translation_of_original: Web/JavaScript/Reference/Global_Objects/Boolean/prototype ---- -
{{JSRef}}
- -

Boolean.prototype özelliği {{jsxref ("Boolean")}} yapıcı methodunun prototipini temsil eder.

- -
{{js_property_attributes(0, 0, 0)}}
- -
{{EmbedInteractiveExample("pages/js/boolean-constructor.html")}}
- - - -

 

- -

{{jsxref("Boolean")}} instances inherit from Boolean.prototype. You can use the constructor's prototype object to add properties or methods to all {{jsxref("Boolean")}} instances.

- -

Properties

- -
-
Boolean.prototype.constructor
-
Bir örneğin prototipini oluşturan fonksiyonu döndürür. Bu varsayılan olarak {{jsxref ("Boolean")}} işlevidir.
-
- -

Methods

- -
-
{{jsxref("Boolean.prototype.toSource()")}} {{non-standard_inline}}
-
{{Jsxref ("Boolean")}} nesnesinin kaynağını içeren bir dize döndürür; eşdeğer bir nesne oluşturmak için bu dizeyi kullanabilirsiniz. {{Jsxref ("Object.prototype.toSource ()")}} methodunu geçersiz kılar.
-
{{jsxref("Boolean.prototype.toString()")}}
-
Nesnenin değerine bağlı olarak "true" ya da "false" dizesini döndürür. {{Jsxref ("Object.prototype.toString ()")}} methodunu geçersiz kılar.
-
{{jsxref("Boolean.prototype.valueOf()")}}
-
{{Jsxref ("Boolean")}} nesnesinin temel değerini döndürür. {{Jsxref ("Object.prototype.valueOf ()")}} methodunu geçersiz kılar.
-
- -

Özellikler

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ÖzelliklerDurumAçıklama
{{SpecName('ES1')}}{{Spec2('ES1')}}İlk tanım. JavaScript 1.0'da uygulanmaktadır.
{{SpecName('ES5.1', '#sec-15.6.3.1', 'Boolean.prototype')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-boolean.prototype', 'Boolean.prototype')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-boolean.prototype', 'Boolean.prototype')}}{{Spec2('ESDraft')}} 
- -

Tarayıcı Uyumluluğu

- -
- - -

{{Compat("javascript.builtins.Boolean.prototype")}}

-
diff --git a/files/tr/web/javascript/reference/global_objects/map/prototype/index.html b/files/tr/web/javascript/reference/global_objects/map/prototype/index.html deleted file mode 100644 index 1124f3602e..0000000000 --- a/files/tr/web/javascript/reference/global_objects/map/prototype/index.html +++ /dev/null @@ -1,85 +0,0 @@ ---- -title: Map.prototype -slug: Web/JavaScript/Reference/Global_Objects/Map/prototype -translation_of: Web/JavaScript/Reference/Global_Objects/Map -translation_of_original: Web/JavaScript/Reference/Global_Objects/Map/prototype ---- -
{{JSRef}}
- -

Map.prototype özelliği {{jsxref("Map")}} kurucusunun prototipini temsil eder.

- -
{{js_property_attributes(0,0,0)}}
- -

Tanım

- -

{{jsxref("Map")}} örnekleri {{jsxref("Map.prototype")}}'den miras alınır. Tüm Map örneklerine özellikler veya yöntemler eklemek için yapıcının prototip nesnesini kullanabilirsiniz.

- -

Özellikleri

- -
-
Map.prototype.constructor
-
Bir örneğin prototipini oluşturan işlevi döndürür. Bu, varsayılan olarak {{jsxref("Map")}} işlevidir.
-
{{jsxref("Map.prototype.size")}}
-
Map nesnesindeki anahtar / değer çiftlerinin sayısını döndürür.
-
- -

Yöntemler

- -
-
{{jsxref("Map.prototype.clear()")}}
-
Tüm anahtar / değer çiftlerini Map objesinden siler.
-
{{jsxref("Map.delete", "Map.prototype.delete(key)")}}
-
Map nesnesindeki bir öge varsa ve kaldırılmışsa true öge yoksa false döndürür. Map.prototype.has(key) daha sonra false döndürür.
-
{{jsxref("Map.prototype.entries()")}}
-
Ekleme sırasındaki Map nesnesindeki her öge için [anahtar, değer] dizisini içeren yeni bir Iterator nesnesini döndürür.
-
{{jsxref("Map.forEach", "Map.prototype.forEach(callbackFn[, thisArg])")}}
-
Map nesnesindeki her anahtar - değer çifti için ekleme sırasına göre callbackFn ögesini bir kez çağırır.  thisArg parametresi forEach için sağlanmışsa, her geri çağırma için bu değer olarak kullanılacaktır.
-
{{jsxref("Map.get", "Map.prototype.get(key)")}}
-
key ile ilişkilendirilmiş değeri veya hiçbir şey yoksa undefined değerini döndürür.
-
{{jsxref("Map.has", "Map.prototype.has(key)")}}
-
Map nesnesindeki bir değerin key ile ilişkili olup olmadığını belirten bir boolean döndürür.
-
{{jsxref("Map.prototype.keys()")}}
-
Map nesnesindeki her bir ögenin anahtarlarını ekleme sırasına göre içeren yeni bir Iterator nesnesi döndürür.
-
{{jsxref("Map.set", "Map.prototype.set(key, value)")}}
-
Mapnesnesindeki key değerini ayarlar. Map nesnesini döndürür.
-
{{jsxref("Map.prototype.values()")}}
-
Map nesnesindeki her bir ögenin değerlerini ekleme sırasına göre içeren yeni bir  Iterator nesnesi döndürür.
-
{{jsxref("Map.@@iterator", "Map.prototype[@@iterator]()")}}
-
Ekleme sırasındaki Map nesnesindeki her bir öge için[anahtar, değer] dizisini içeren yeni bir Iterator nesnesini döndürür.
-
- -

Şartlar

- - - - - - - - - - - - - - - - - - - -
ŞartDurumAçıklama
{{SpecName('ES2015', '#sec-map.prototype', 'Map.prototype')}}{{Spec2('ES2015')}} -

İlk tanım

-
{{SpecName('ESDraft', '#sec-map.prototype', 'Map.prototype')}}{{Spec2('ESDraft')}} 
- -

Tarayıcı Uyumluluğu

- - - -

{{Compat("javascript.builtins.Map.prototype")}}

- -

Ayrıca Bakınız

- - diff --git a/files/tr/web/javascript/reference/operators/function_star_/index.html b/files/tr/web/javascript/reference/operators/function_star_/index.html new file mode 100644 index 0000000000..193e00f205 --- /dev/null +++ b/files/tr/web/javascript/reference/operators/function_star_/index.html @@ -0,0 +1,84 @@ +--- +title: function* expression +slug: Web/JavaScript/Reference/Operatörler/function* +translation_of: Web/JavaScript/Reference/Operators/function* +--- +
{{jsSidebar("Operators")}}
+ +

The function* keyword can be used to define a generator function inside an expression.

+ +
{{EmbedInteractiveExample("pages/js/expressions-functionasteriskexpression.html")}}
+ + + +

Syntax

+ +
function* [name]([param1[, param2[, ..., paramN]]]) {
+   statements
+}
+ +

Parametreler

+ +
+
name
+
The function name. Can be omitted, in which case the function is anonymous. The name is only local to the function body.
+
paramN
+
Argüman adıdır, bir fonksiyon maxiumum 255 argüman alır.
+
statements
+
Fonksiyon kodları.
+
+ +

Açıklama

+ +

A function* expression is very similar to and has almost the same syntax as a {{jsxref('Statements/function*', 'function* statement')}}. The main difference between a function* expression and a function* statement is the function name, which can be omitted in function* expressions to create anonymous generator functions. See also the chapter about functions for more information.

+ +

Örnekler

+ +

Aşağıdaki adlandırılmamış fonksiyondur ve gelen değer karesini verir.

+ +
var x = function*(y) {
+   yield y * y;
+};
+
+ +

Özellikler

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#', 'function*')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#', 'function*')}}{{Spec2('ESDraft')}} 
+ +

Tarayıcı uyumluluğu

+ + + +

{{Compat("javascript.operators.function_star")}}

+ +

Bakabilirsiniz

+ + diff --git a/files/tr/web/javascript/reference/operators/index.html b/files/tr/web/javascript/reference/operators/index.html new file mode 100644 index 0000000000..f42305b092 --- /dev/null +++ b/files/tr/web/javascript/reference/operators/index.html @@ -0,0 +1,277 @@ +--- +title: İfadeler ve operatörler +slug: Web/JavaScript/Reference/Operatörler +translation_of: Web/JavaScript/Reference/Operators +--- +
{{jsSidebar("Operators")}}
+ +

Bu döküman bütün JavaScript ifadelerini,operatörlerini ve anahtar kelimeleri içerir.

+ +

Expressions and operators by category

+ +

For an alphabetical listing see the sidebar on the left.

+ +

Birincil İfadeler

+ +

Genel İfadeler ve basit anahtar kelimeler.

+ +
+
{{jsxref("Operators/this", "this")}}
+
The this keyword refers to the function's execution context.
+
{{jsxref("Operators/function", "function")}}
+
The function keyword defines a function expression.
+
{{experimental_inline}} {{jsxref("Operators/class", "class")}}
+
The class keyword defines a class expression.
+
{{experimental_inline}} {{jsxref("Operators/function*", "function*")}}
+
The function* keyword defines a generator function expression.
+
{{experimental_inline}} {{jsxref("Operators/yield", "yield")}}
+
Pause and resume a generator function
+
{{experimental_inline}} {{jsxref("Operators/yield*", "yield*")}}
+
Delegate to another generator function or iterable object.
+
{{jsxref("Global_Objects/Array", "[]")}}
+
Array initializer/literal syntax.
+
{{jsxref("Operators/Object_initializer", "{}")}}
+
Object initializer/literal syntax.
+
{{jsxref("Global_Objects/RegExp", "/ab+c/i")}}
+
Regular expression literal syntax.
+
{{experimental_inline}} {{jsxref("Operators/Array_comprehensions", "[for (x of y) x]")}}
+
Array comprehensions.
+
{{experimental_inline}} {{jsxref("Operators/Generator_comprehensions", "(for (x of y) y)")}}
+
Generator comprehensions.
+
{{jsxref("Operators/Grouping", "( )")}}
+
Grouping operator.
+
+ +

Left-hand-side expressions

+ +

Left values are the destination of an assignment.

+ +
+
{{jsxref("Operators/Property_accessors", "Property accessors", "", 1)}}
+
Member operators provide access to a property or method of an object
+ (object.property and object["property"]).
+
{{jsxref("Operators/new", "new")}}
+
The new operator creates an instance of a constructor.
+
{{experimental_inline}} {{jsxref("Operators/super", "super")}}
+
The super keyword calls the parent constructor.
+
{{experimental_inline}} {{jsxref("Operators/Spread_operator", "...obj")}}
+
The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.
+
+ +

Increment and decrement

+ +

Postfix/prefix increment and postfix/prefix decrement operators.

+ +
+
{{jsxref("Operators/Arithmetic_Operators", "A++", "#Increment")}}
+
Postfix increment operator.
+
{{jsxref("Operators/Arithmetic_Operators", "A--", "#Decrement")}}
+
Postfix decrement operator.
+
{{jsxref("Operators/Arithmetic_Operators", "++A", "#Increment")}}
+
Prefix increment operator.
+
{{jsxref("Operators/Arithmetic_Operators", "--A", "#Decrement")}}
+
Prefix decrement operator.
+
+ +

Unary operators

+ +

A unary operation is operation with only one operand.

+ +
+
{{jsxref("Operators/delete", "delete")}}
+
The delete operator deletes a property from an object.
+
{{jsxref("Operators/void", "void")}}
+
The void operator discards an expression's return value.
+
{{jsxref("Operators/typeof", "typeof")}}
+
The typeof operator determines the type of a given object.
+
{{jsxref("Operators/Arithmetic_Operators", "+", "#Unary_plus")}}
+
The unary plus operator converts its operand to Number type.
+
{{jsxref("Operators/Arithmetic_Operators", "-", "#Unary_negation")}}
+
The unary negation operator converts its operand to Number type and then negates it.
+
{{jsxref("Operators/Bitwise_Operators", "~", "#Bitwise_NOT")}}
+
Bitwise NOT operator.
+
{{jsxref("Operators/Logical_Operators", "!", "#Logical_NOT")}}
+
Logical NOT operator.
+
+ +

Arithmetic operators

+ +

Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value.

+ +
+
{{jsxref("Operators/Arithmetic_Operators", "+", "#Addition")}}
+
Addition operator.
+
{{jsxref("Operators/Arithmetic_Operators", "-", "#Subtraction")}}
+
Subtraction operator.
+
{{jsxref("Operators/Arithmetic_Operators", "/", "#Division")}}
+
Division operator.
+
{{jsxref("Operators/Arithmetic_Operators", "*", "#Multiplication")}}
+
Multiplication operator.
+
{{jsxref("Operators/Arithmetic_Operators", "%", "#Remainder")}}
+
Remainder operator.
+
+ +

Relational operators

+ +

A comparison operator compares its operands and returns a Boolean value based on whether the comparison is true.

+ +
+
{{jsxref("Operators/in", "in")}}
+
The in operator determines whether an object has a given property.
+
{{jsxref("Operators/instanceof", "instanceof")}}
+
The instanceof operator determines whether an object is an instance of another object.
+
{{jsxref("Operators/Comparison_Operators", "<", "#Less_than_operator")}}
+
Less than operator.
+
{{jsxref("Operators/Comparison_Operators", ">", "#Greater_than_operator")}}
+
Greater than operator.
+
{{jsxref("Operators/Comparison_Operators", "<=", "#Less_than_or_equal_operator")}}
+
Less than or equal operator.
+
{{jsxref("Operators/Comparison_Operators", ">=", "#Greater_than_or_equal_operator")}}
+
Greater than or equal operator.
+
+ +

Equality operators

+ +

The result of evaluating an equality operator is always of type Boolean based on whether the comparison is true.

+ +
+
{{jsxref("Operators/Comparison_Operators", "==", "#Equality")}}
+
Equality operator.
+
{{jsxref("Operators/Comparison_Operators", "!=", "#Inequality")}}
+
Inequality operator.
+
{{jsxref("Operators/Comparison_Operators", "===", "#Identity")}}
+
Identity operator.
+
{{jsxref("Operators/Comparison_Operators", "!==", "#Nonidentity")}}
+
Nonidentity operator.
+
+ +

Bitwise shift operators

+ +

Operations to shift all bits of the operand.

+ +
+
{{jsxref("Operators/Bitwise_Operators", "<<", "#Left_shift")}}
+
Bitwise left shift operator.
+
{{jsxref("Operators/Bitwise_Operators", ">>", "#Right_shift")}}
+
Bitwise right shift operator.
+
{{jsxref("Operators/Bitwise_Operators", ">>>", "#Unsigned_right_shift")}}
+
Bitwise unsigned right shift operator.
+
+ +

Binary bitwise operators

+ +

Bitwise operators treat their operands as a set of 32 bits (zeros and ones) and return standard JavaScript numerical values.

+ +
+
{{jsxref("Operators/Bitwise_Operators", "&", "#Bitwise_AND")}}
+
Bitwise AND.
+
{{jsxref("Operators/Bitwise_Operators", "|", "#Bitwise_OR")}}
+
Bitwise OR.
+
{{jsxref("Operators/Bitwise_Operators", "^", "#Bitwise_XOR")}}
+
Bitwise XOR.
+
+ +

Binary logical operators

+ +

Logical operators are typically used with boolean (logical) values, and when they are, they return a boolean value.

+ +
+
{{jsxref("Operators/Logical_Operators", "&&", "#Logical_AND")}}
+
Logical AND.
+
{{jsxref("Operators/Logical_Operators", "||", "#Logical_OR")}}
+
Logical OR.
+
+ +

Conditional (ternary) operator

+ +
+
{{jsxref("Operators/Conditional_Operator", "(condition ? ifTrue : ifFalse)")}}
+
+

The conditional operator returns one of two values based on the logical value of the condition.

+
+
+ +

Assignment operators

+ +

An assignment operator assigns a value to its left operand based on the value of its right operand.

+ +
+
{{jsxref("Operators/Assignment_Operators", "=", "#Assignment")}}
+
Assignment operator.
+
{{jsxref("Operators/Assignment_Operators", "*=", "#Multiplication_assignment")}}
+
Multiplication assignment.
+
{{jsxref("Operators/Assignment_Operators", "/=", "#Division_assignment")}}
+
Division assignment.
+
{{jsxref("Operators/Assignment_Operators", "%=", "#Remainder_assignment")}}
+
Remainder assignment.
+
{{jsxref("Operators/Assignment_Operators", "+=", "#Addition_assignment")}}
+
Addition assignment.
+
{{jsxref("Operators/Assignment_Operators", "-=", "#Subtraction_assignment")}}
+
Subtraction assignment
+
{{jsxref("Operators/Assignment_Operators", "<<=", "#Left_shift_assignment")}}
+
Left shift assignment.
+
{{jsxref("Operators/Assignment_Operators", ">>=", "#Right_shift_assignment")}}
+
Right shift assignment.
+
{{jsxref("Operators/Assignment_Operators", ">>>=", "#Unsigned_right_shift_assignment")}}
+
Unsigned right shift assignment.
+
{{jsxref("Operators/Assignment_Operators", "&=", "#Bitwise_AND_assignment")}}
+
Bitwise AND assignment.
+
{{jsxref("Operators/Assignment_Operators", "^=", "#Bitwise_XOR_assignment")}}
+
Bitwise XOR assignment.
+
{{jsxref("Operators/Assignment_Operators", "|=", "#Bitwise_OR_assignment")}}
+
Bitwise OR assignment.
+
{{experimental_inline}} {{jsxref("Operators/Destructuring_assignment", "[a, b] = [1, 2]")}}
+ {{experimental_inline}} {{jsxref("Operators/Destructuring_assignment", "{a, b} = {a:1, b:2}")}}
+
+

Destructuring assignment allows you to assign the properties of an array or object to variables using syntax that looks similar to array or object literals.

+
+
+ +

Comma operator

+ +
+
{{jsxref("Operators/Comma_Operator", ",")}}
+
The comma operator allows multiple expressions to be evaluated in a single statement and returns the result of the last expression.
+
+ +

Non-standard features

+ +
+
{{non-standard_inline}} {{jsxref("Operators/Legacy_generator_function", "Legacy generator function", "", 1)}}
+
The function keyword can be used to define a legacy generator function inside an expression. To make the function a legacy generator, the function body should contains at least one {{jsxref("Operators/yield", "yield")}} expression.
+
{{non-standard_inline}} {{jsxref("Operators/Expression_closures", "Expression closures", "", 1)}}
+
The expression closure syntax is a shorthand for writing simple function.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
ECMAScript 1st Edition.StandardInitial definition.
{{SpecName('ES5.1', '#sec-11', 'Expressions')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}{{Spec2('ES6')}}New: Spread operator, destructuring assignment, super keyword, Array comprehensions, Generator comprehensions
+ +

See also

+ + diff --git a/files/tr/web/javascript/reference/operators/instanceof/index.html b/files/tr/web/javascript/reference/operators/instanceof/index.html new file mode 100644 index 0000000000..3434ea34b9 --- /dev/null +++ b/files/tr/web/javascript/reference/operators/instanceof/index.html @@ -0,0 +1,207 @@ +--- +title: instanceof +slug: Web/JavaScript/Reference/Operatörler/instanceof +translation_of: Web/JavaScript/Reference/Operators/instanceof +--- +
{{jsSidebar("Operators")}}
+ +

Instanceof operatorü bir nesne'nin prototip (prototype) zincirinin, belirli bir prototipin kurucu(constructor) metodu olup olmadığını testeder.

+ +

Syntax

+ +
object instanceof constructor
+ +

Parametreler

+ +
+
object
+
Test edilecek nesne
+
+ +
+
constructor
+
Test edilecek karşı kurucu fonksiyon
+
+ +

Açıklama

+ +

Instanceof operatorü nesnenin prototip zincirinde 'constructor.prototype' varlığını testeder.

+ +
// defining constructors
+function C() {}
+function D() {}
+
+var o = new C();
+
+// true, because: Object.getPrototypeOf(o) === C.prototype
+o instanceof C;
+
+// false, because D.prototype is nowhere in o's prototype chain
+o instanceof D;
+
+o instanceof Object; // true, because:
+C.prototype instanceof Object // true
+
+C.prototype = {};
+var o2 = new C();
+
+o2 instanceof C; // true
+
+// false, because C.prototype is nowhere in
+// o's prototype chain anymore
+o instanceof C;
+
+D.prototype = new C(); // add C to [[Prototype]] linkage of D
+var o3 = new D();
+o3 instanceof D; // true
+o3 instanceof C; // true since C.prototype is now in o3's prototype chain
+
+ +

Bir instanceof testinin değerinin yapıcıların prototip özelliklerinde yapılan değişikliklere göre değişebileceğini ve Object.setPrototypeOf kullanılarak bir nesne prototipini değiştirerek de değişebileceğini unutmayın. Standart olmayan __proto__ sözde-özelliği(pseudo-property) kullanarak da mümkündür.

+ +

instanceof ve çoklu bağlam (multiple context) (e.g. frames or windows)

+ +

Farklı kapsamların (Scopes) farklı yürütme (execution) ortamları vardır. Bu, farklı yerleşik yapılara sahip oldukları anlamına gelir (farklı global nesne, farklı yapıcılar, vb.). Bu, beklenmedik sonuçlara neden olabilir. Örneğin, [] instanceof window.frames [0] .Array false döndürür, çünkü Array.prototype! == window.frames [0] .Array ve diziler belli bir dizgeden (former) miras alırlar. Bu başlangıçta mantıklı gelmeyebilir, ancak betiğinizde (script) birden çok cerceve (frame) veya pencereyi (window) ele almaya başladığınızda ve nesneleri fonsiyonlarla bir bağlamdan diğerine geçirirken, bu geçerli ve güçlü bir sayı olacaktır. Örneğin, belirli bir nesnenin aslında Array.isArray (myObj) kullanarak bir Array olup olmadığını güvenli bir şekilde kontrol edebilirsiniz.

+ +
Mozilla geliştiricleri için not: + +

Kodda XPCOM kullanımının özel bir etkisi vardır: obj instanceof xpcomInterface (ör. Components.interfaces.nsIFile), obj.QueryInterface (xpcomInterface) çağırır ve QueryInterface başarılı olursa true değerini döndürür. Bu tür bir aramanın bir yan etkisi, başarılı bir örnekleme sonucunda obj'de xpcomInterface özelliklerini kullanabilmenizdir. Standart JavaScript globals'ın aksine, test obj instance of xpcomInterface, obj farklı bir kapsamdan olsa bile beklendiği gibi çalışır.

+
+ +

Examples

+ +

Demonstrating that String and Date are of type Object and exceptional cases

+ +

The following code uses instanceof to demonstrate that String and Date objects are also of type Object (they are derived from Object).

+ +

However, objects created with the object literal notation are an exception here: Although the prototype is undefined, instanceof Object returns true.

+ +
var simpleStr = 'This is a simple string';
+var myString  = new String();
+var newStr    = new String('String created with constructor');
+var myDate    = new Date();
+var myObj     = {};
+
+simpleStr instanceof String; // returns false, checks the prototype chain, finds undefined
+myString  instanceof String; // returns true
+newStr    instanceof String; // returns true
+myString  instanceof Object; // returns true
+
+myObj instanceof Object;    // returns true, despite an undefined prototype
+({})  instanceof Object;    // returns true, same case as above
+
+myString instanceof Date;   // returns false
+
+myDate instanceof Date;     // returns true
+myDate instanceof Object;   // returns true
+myDate instanceof String;   // returns false
+
+ +

Demonstrating that mycar is of type Car and type Object

+ +

The following code creates an object type Car and an instance of that object type, mycar. The instanceof operator demonstrates that the mycar object is of type Car and of type Object.

+ +
function Car(make, model, year) {
+  this.make = make;
+  this.model = model;
+  this.year = year;
+}
+var mycar = new Car('Honda', 'Accord', 1998);
+var a = mycar instanceof Car;    // returns true
+var b = mycar instanceof Object; // returns true
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-relational-operators', 'Relational Operators')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-relational-operators', 'Relational Operators')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.8.6', 'The instanceof operator')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-11.8.6', 'The instanceof operator')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.4.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/tr/web/javascript/reference/operators/super/index.html b/files/tr/web/javascript/reference/operators/super/index.html new file mode 100644 index 0000000000..3dd3f62ebf --- /dev/null +++ b/files/tr/web/javascript/reference/operators/super/index.html @@ -0,0 +1,165 @@ +--- +title: super +slug: Web/JavaScript/Reference/Operatörler/super +translation_of: Web/JavaScript/Reference/Operators/super +--- +
{{jsSidebar("Operators")}}
+ +

super, ebeveyn sınıftaki fonksiyonlara ulaşmak ve onları çağırmak için kullanılan bir ifadedir.

+ +

The super.prop and super[expr] expressions are valid in any method definition in both classes and object literals.

+ +

Sözdizimi (Syntax)

+ +
super([arguments]); // ebeveyn sınıfın constructot'ını çağırır.
+super.functionOnParent([arguments]); // ebeveyn sınıftaki functionOnParent fonksiyonunu çalıştırır.
+
+ +

Açıklama

+ +

Constructor içinde super ifadesi tek başına kullanılır ve this ifadesinden önce kullanılması zorunludur. Aynı zamanda super ifadesi ebeveyn sınıftaki fonksiyonları çağırmak için de kullanılabilir.

+ +

Örnekler

+ +

Sınflarda super kullanımı

+ +

This code snippet is taken from the classes sample (live demo). Here super() is called to avoid duplicating the constructor parts' that are common between Rectangle and Square.

+ +
class Rectangle {
+  constructor(height, width) {
+    this.name = 'Rectangle';
+    this.height = height;
+    this.width = width;
+  }
+  sayName() {
+    console.log('Hi, I am a ', this.name + '.');
+  }
+  get area() {
+    return this.height * this.width;
+  }
+  set area(value) {
+    this._area = value;
+  }
+}
+
+class Square extends Rectangle {
+  constructor(length) {
+    this.height; // ReferenceError, super needs to be called first!
+
+    // Here, it calls the parent class's constructor with lengths
+    // provided for the Rectangle's width and height
+    super(length, length);
+
+    // Note: In derived classes, super() must be called before you
+    // can use 'this'. Leaving this out will cause a reference error.
+    this.name = 'Square';
+  }
+}
+ +

Super-calling static methods

+ +

You are also able to call super on static methods.

+ +
class Rectangle {
+  static logNbSides() {
+    return 'I have 4 sides';
+  }
+}
+
+class Square extends Rectangle {
+  static logDescription() {
+    return super.logNbSides() + ' which are all equal';
+  }
+}
+Square.logDescription(); // 'I have 4 sides which are all equal'
+
+ +

Deleting super properties will throw an error

+ +

You cannot use the delete operator and super.prop or super[expr] to delete a parent class' property, it will throw a {{jsxref("ReferenceError")}}.

+ +
class Base {
+  foo() {}
+}
+class Derived extends Base {
+  delete() {
+    delete super.foo; // this is bad
+  }
+}
+
+new Derived().delete(); // ReferenceError: invalid delete involving 'super'. 
+ +

super.prop cannot overwrite non-writable properties

+ +

When defining non-writable properties with e.g. {{jsxref("Object.defineProperty")}}, super cannot overwrite the value of the property.

+ +
class X {
+  constructor() {
+    Object.defineProperty(this, 'prop', {
+      configurable: true,
+      writable: false,
+      value: 1
+    });
+  }
+}
+
+class Y extends X {
+  constructor() {
+    super();
+  }
+  foo() {
+    super.prop = 2;   // Cannot overwrite the value.
+  }
+}
+
+var y = new Y();
+y.foo(); // TypeError: "prop" is read-only
+console.log(y.prop); // 1
+
+ +

Using super.prop in object literals

+ +

Super can also be used in the object initializer / literal notation. In this example, two objects define a method. In the second object, super calls the first object's method. This works with the help of {{jsxref("Object.setPrototypeOf()")}} with which we are able to set the prototype of obj2 to obj1, so that super is able to find method1 on obj1.

+ +
var obj1 = {
+  method1() {
+    console.log('method 1');
+  }
+}
+
+var obj2 = {
+  method2() {
+    super.method1();
+  }
+}
+
+Object.setPrototypeOf(obj2, obj1);
+obj2.method2(); // logs "method 1"
+
+ +

Özellikler

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-super-keyword', 'super')}}
+ +

Tarayıcı uyumluluğu

+ + + +

{{Compat("javascript.operators.super")}}

+ +

Ayrıca bakınız

+ + diff --git a/files/tr/web/javascript/reference/operators/this/index.html b/files/tr/web/javascript/reference/operators/this/index.html new file mode 100644 index 0000000000..674e577187 --- /dev/null +++ b/files/tr/web/javascript/reference/operators/this/index.html @@ -0,0 +1,347 @@ +--- +title: this +slug: Web/JavaScript/Reference/Operatörler/this +translation_of: Web/JavaScript/Reference/Operators/this +--- +
{{jsSidebar("Operators")}}
+ +

Fonksiyon'un this anahtar kelimesi diğer dillere göre birazcık farklı davranır. Ayrıca strict modu ve non-strict modu arasında farklılıklar bulunur.

+ +

Çoğunlukla, this'in değeri fonksiyonun çağrılma biçimine göre belirlenir. Çalışma esnasında değeri değiştirilemez, ve her fonksiyonu çağırışta farklı olabilir. ES5 bu adreste bind method to set the value of a function's this regardless of how it's called.

+ +

Sözdizimi

+ +
this
+ +

Global içerik

+ +

Global konumda (fonksiyon dışında), this global nesnesini referans gösterir, strict modunda olmak bu durumu değiştirmez..

+ +
console.log(this.document === document); // true
+
+// Web browserlerinde window objesi global objedir.:
+console.log(this === window); // true
+
+this.a = 37;
+console.log(window.a); // 37
+
+ +

Function içerik

+ +

Fonksiyon içerisinde, this'in değeri fonksiyonun nasıl çağrıldığına bağlıdır..

+ +

Basit çağrı

+ +
function f1(){
+  return this;
+}
+
+f1() === window; // global obje
+
+ +

Bu durumda, this'in değeri çağrı ile ayarlanmaz. Kod strict modda olmadığı sürece, this'in değeri mutlaka obje olmalıdır bu yüzdende default değer olan global objesi döner.

+ +
function f2(){
+  "use strict"; // strict modu içerisinde çalıştıralım
+  return this;
+}
+
+f2() === undefined;
+
+ +

Strict modu içerisinde, this'in değeri çalıştırılma içeriğine nasıl girdiyse o şekilde kalır. Eğer tanımlanmamışsa, undefined olarak kalır. Ayrıca tüm değerlere eşitlenebilir, örneğin null yada 42 yada "I am not this".

+ +
Not: İkinci örnekte, this undefined olmalıdır, çünkü f2 taban belirtilmeden çağrılmıştır. (örn: window.f2()). Bu özellik bazı browserlerde desteklenmemektedir. strict mod henüz geliştirme aşamasındayken çoğu browser yanlış davranarak window objesini döndürür.
+ +

Obje methodu cağrısı

+ +

Fonksiyon bir objenin methodu olarak çağrıldığında, this çağrıldığı obje olarak atanacaktır.

+ +

In the following example, when o.f() is invoked, inside the function this is bound to the o object.

+ +
var o = {
+  prop: 37,
+  f: function() {
+    return this.prop;
+  }
+};
+
+console.log(o.f()); // logs 37
+
+ +

Note that this behavior is not at all affected by how or where the function was defined. In the previous example, we defined the function inline as the f member during the definition of o. However, we could have just as easily defined the function first and later attached it to o.f. Doing so results in the same behavior:

+ +
var o = {prop: 37};
+
+function independent() {
+  return this.prop;
+}
+
+o.f = independent;
+
+console.log(o.f()); // logs 37
+
+ +

This demonstrates that it matters only that the function was invoked from the f member of o.

+ +

Similarly, the this binding is only affected by the most immediate member reference. In the following example, when we invoke the function, we call it as a method g of the object o.b. This time during execution, this inside the function will refer to o.b. The fact that the object is itself a member of o has no consequence; the most immediate reference is all that matters.

+ +
o.b = {g: independent, prop: 42};
+console.log(o.b.g()); // logs 42
+
+ +

this on the object's prototype chain

+ +

The same notion holds true for methods defined somewhere on the object's prototype chain. If the method is on an object's prototype chain, this refers to the object the method was called on, as if the method was on the object.

+ +
var o = {f:function(){ return this.a + this.b; }};
+var p = Object.create(o);
+p.a = 1;
+p.b = 4;
+
+console.log(p.f()); // 5
+
+ +

In this example, the object assigned to the variable p doesn't have its own f property, it inherits it from its prototype. But it doesn't matter that the lookup for f eventually finds a member with that name on o; the lookup began as a reference to p.f, so this inside the function takes the value of the object referred to as p. That is, since f is called as a method of p, its this refers to p. This is an interesting feature of JavaScript's prototype inheritance.

+ +

this with a getter or setter

+ +

Again, the same notion holds true when a function is invoked from a getter or a setter. A function used as getter or setter has its this bound to the object from which the property is being set or gotten.

+ +
function modulus(){
+  return Math.sqrt(this.re * this.re + this.im * this.im);
+}
+
+var o = {
+  re: 1,
+  im: -1,
+  get phase(){
+    return Math.atan2(this.im, this.re);
+  }
+};
+
+Object.defineProperty(o, 'modulus', {
+    get: modulus, enumerable:true, configurable:true});
+
+console.log(o.phase, o.modulus); // logs -0.78 1.4142
+
+ +

As a constructor

+ +

When a function is used as a constructor (with the new keyword), its this is bound to the new object being constructed.

+ +

Note: while the default for a constructor is to return the object referenced by this, it can instead return some other object (if the return value isn't an object, then the this object is returned).

+ +
/*
+ * Constructors work like this:
+ *
+ * function MyConstructor(){
+ *   // Actual function body code goes here.
+ *   // Create properties on |this| as
+ *   // desired by assigning to them.  E.g.,
+ *   this.fum = "nom";
+ *   // et cetera...
+ *
+ *   // If the function has a return statement that
+ *   // returns an object, that object will be the
+ *   // result of the |new| expression.  Otherwise,
+ *   // the result of the expression is the object
+ *   // currently bound to |this|
+ *   // (i.e., the common case most usually seen).
+ * }
+ */
+
+function C(){
+  this.a = 37;
+}
+
+var o = new C();
+console.log(o.a); // logs 37
+
+
+function C2(){
+  this.a = 37;
+  return {a:38};
+}
+
+o = new C2();
+console.log(o.a); // logs 38
+
+ +

In the last example (C2), because an object was returned during construction, the new object that this was bound to simply gets discarded. (This essentially makes the statement "this.a = 37;" dead code. It's not exactly dead, because it gets executed, but it can be eliminated with no outside effects.)

+ +

call and apply

+ +

Where a function uses the this keyword in its body, its value can be bound to a particular object in the call using the call or apply methods that all functions inherit from Function.prototype.

+ +
function add(c, d){
+  return this.a + this.b + c + d;
+}
+
+var o = {a:1, b:3};
+
+// The first parameter is the object to use as
+// 'this', subsequent parameters are passed as
+// arguments in the function call
+add.call(o, 5, 7); // 1 + 3 + 5 + 7 = 16
+
+// The first parameter is the object to use as
+// 'this', the second is an array whose
+// members are used as the arguments in the function call
+add.apply(o, [10, 20]); // 1 + 3 + 10 + 20 = 34
+
+ +

Note that with call and apply, if the value passed as this is not an object, an attempt will be made to convert it to an object using the internal ToObject operation. So if the value passed is a primitive like 7 or 'foo', it will be converted to an Object using the related constructor, so the primitive number 7 is converted to an object as if by new Number(7) and the string 'foo' to an object as if by new String('foo'), e.g.

+ +
function bar() {
+  console.log(Object.prototype.toString.call(this));
+}
+
+bar.call(7); // [object Number]
+
+ +

The bind method

+ +

ECMAScript 5 introduced Function.prototype.bind. Calling f.bind(someObject) creates a new function with the same body and scope as f, but where this occurs in the original function, in the new function it is permanently bound to the first argument of bind, regardless of how the function is being used.

+ +
function f(){
+  return this.a;
+}
+
+var g = f.bind({a:"azerty"});
+console.log(g()); // azerty
+
+var o = {a:37, f:f, g:g};
+console.log(o.f(), o.g()); // 37, azerty
+
+ +

As a DOM event handler

+ +

When a function is used as an event handler, its this is set to the element the event fired from (some browsers do not follow this convention for listeners added dynamically with methods other than addEventListener).

+ +
// When called as a listener, turns the related element blue
+function bluify(e){
+  // Always true
+  console.log(this === e.currentTarget);
+  // true when currentTarget and target are the same object
+  console.log(this === e.target);
+  this.style.backgroundColor = '#A5D9F3';
+}
+
+// Get a list of every element in the document
+var elements = document.getElementsByTagName('*');
+
+// Add bluify as a click listener so when the
+// element is clicked on, it turns blue
+for(var i=0 ; i<elements.length ; i++){
+  elements[i].addEventListener('click', bluify, false);
+}
+ +

In an in–line event handler

+ +

When code is called from an in–line handler, its this is set to the DOM element on which the listener is placed:

+ +
<button onclick="alert(this.tagName.toLowerCase());">
+  Show this
+</button>
+
+ +

The above alert shows button. Note however that only the outer code has its this set this way:

+ +
<button onclick="alert((function(){return this}()));">
+  Show inner this
+</button>
+
+ +

In this case, the inner function's this isn't set so it returns the global/window object (i.e. the default object in non–strict mode where this isn't set by the call).

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-this-keyword', 'The this keyword')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.1.1', 'The this keyword')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-11.1.1', 'The this keyword')}}{{Spec2('ES3')}} 
{{SpecName('ES1', '#sec-11.1.1', 'The this keyword')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/tr/web/javascript/reference/operators/typeof/index.html b/files/tr/web/javascript/reference/operators/typeof/index.html new file mode 100644 index 0000000000..deccfd8925 --- /dev/null +++ b/files/tr/web/javascript/reference/operators/typeof/index.html @@ -0,0 +1,259 @@ +--- +title: typeof +slug: Web/JavaScript/Reference/Operatörler/typeof +translation_of: Web/JavaScript/Reference/Operators/typeof +--- +
{{jsSidebar("Operatörler")}}
+ +

Typeof operatörü, değerlendirilmemiş işlenenin türünü gösteren bir dize döndürür.

+ +
{{EmbedInteractiveExample("pages/js/expressions-typeof.html")}}
+ + + +

Sözdizimi

+ +

The typeof operator is followed by its operand:

+ +
typeof operand
+or
+typeof (operand)
+
+ + + +

Parametreler

+ +

operand is an expression representing the object or {{Glossary("Primitive", "primitive")}} whose type is to be returned.

+ +

Parantez isteğe bağlıdır.

+ +

Description

+ +

The following table summarizes the possible return values of typeof. For more information about types and primitives, see also the JavaScript data structure page.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TypeResult
Undefined"undefined"
Null"object" (see below)
Boolean"boolean"
Number"number"
String"string"
Symbol (new in ECMAScript 2015)"symbol"
Host object (provided by the JS environment)Implementation-dependent
Function object (implements [[Call]] in ECMA-262 terms)"function"
Any other object"object"
+ +

Örnekler

+ +
// Sayılar
+typeof 37 === 'number';
+typeof 3.14 === 'number';
+typeof(42) === 'number';
+typeof Math.LN2 === 'number';
+typeof Infinity === 'number';
+typeof NaN === 'number'; // Despite being "Not-A-Number"
+typeof Number(1) === 'number'; // but never use this form!
+
+
+// Metinler
+typeof '' === 'string';
+typeof 'bla' === 'string';
+typeof '1' === 'string'; // note that a number within a string is still typeof string
+typeof (typeof 1) === 'string'; // typeof always returns a string
+typeof String('abc') === 'string'; // but never use this form!
+
+
+// Booleans
+typeof true === 'boolean';
+typeof false === 'boolean';
+typeof Boolean(true) === 'boolean'; // but never use this form!
+
+
+// Symbols
+typeof Symbol() === 'symbol'
+typeof Symbol('foo') === 'symbol'
+typeof Symbol.iterator === 'symbol'
+
+
+// Undefined
+typeof undefined === 'undefined';
+typeof declaredButUndefinedVariable === 'undefined';
+typeof undeclaredVariable === 'undefined';
+
+
+// Objeler
+typeof {a: 1} === 'object';
+
+// use Array.isArray or Object.prototype.toString.call
+// to differentiate regular objects from arrays
+typeof [1, 2, 4] === 'object';
+
+typeof new Date() === 'object';
+
+
+// The following is confusing. Don't use!
+typeof new Boolean(true) === 'object';
+typeof new Number(1) === 'object';
+typeof new String('abc') === 'object';
+
+
+// Fonksiyonlar
+typeof function() {} === 'function';
+typeof class C {} === 'function';
+typeof Math.sin === 'function';
+
+ +

null

+ +
// This stands since the beginning of JavaScript
+typeof null === 'object';
+
+ +

In the first implementation of JavaScript, JavaScript values were represented as a type tag and a value. The type tag for objects was 0. null was represented as the NULL pointer (0x00 in most platforms). Consequently, null had 0 as type tag, hence the bogus typeof return value. (reference)

+ +

A fix was proposed for ECMAScript (via an opt-in), but was rejected. It would have resulted in typeof null === 'null'.

+ +

new operatör kullanımı

+ +
// All constructor functions while instantiated with 'new' keyword will always be typeof 'object'
+var str = new String('String');
+var num = new Number(100);
+
+typeof str; // It will return 'object'
+typeof num; // It will return 'object'
+
+// But there is a exception in case of Function constructor of Javascript
+
+var func = new Function();
+
+typeof func; // It will return 'function'
+
+ +

Parantezlere ihtiyaç var

+ +
// Parentheses will be very much useful to determine the data type for expressions.
+var iData = 99;
+
+typeof iData + ' Wisen'; // It will return 'number Wisen'
+typeof (iData + ' Wisen'); // It will return 'string'
+
+
+
+ +

Düzenli İfadeler

+ +

Callable regular expressions were a non-standard addition in some browsers.

+ +
typeof /s/ === 'function'; // Chrome 1-12 Non-conform to ECMAScript 5.1
+typeof /s/ === 'object';   // Firefox 5+  Conform to ECMAScript 5.1
+
+ +

Temporal Dead Zone errors

+ +

Before ECMAScript 2015, typeof was always guaranteed to return a string for any operand it was supplied with. But with the addition of non-hoisted, block-scoped let and const, using typeof on let and const variables in a block before they are declared will throw a ReferenceError. This is in contrast with undeclared variables, for which typeof will return 'undefined'. Block scoped variables are in a "temporal dead zone" from the start of the block until the initialization is processed, during which, it will throw an error if accessed.

+ +
typeof undeclaredVariable === 'undefined';
+typeof newLetVariable; let newLetVariable; // ReferenceError
+typeof newConstVariable; const newConstVariable = 'hello'; // ReferenceError
+
+ +

İstisnalar

+ +

All current browsers expose a non-standard host object {{domxref("document.all")}} with type Undefined.

+ +
typeof document.all === 'undefined';
+
+ +

Although the specification allows custom type tags for non-standard exotic objects, it requires those type tags to be different from the predefined ones. The case of document.all having type tag 'undefined' must be classified as an exceptional violation of the rules.

+ +

Özellikler

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-typeof-operator', 'The typeof Operator')}}{{Spec2('ESDraft')}}
{{SpecName('ES6', '#sec-typeof-operator', 'The typeof Operator')}}{{Spec2('ES6')}}
{{SpecName('ES5.1', '#sec-11.4.3', 'The typeof Operator')}}{{Spec2('ES5.1')}}
{{SpecName('ES3', '#sec-11.4.3', 'The typeof Operator')}}{{Spec2('ES3')}}
{{SpecName('ES1', '#sec-11.4.3', 'The typeof Operator')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
+ +

Browser compatibility

+ + + +

{{Compat("javascript.operators.typeof")}}

+ +

IE özel notlar

+ +

On IE 6, 7, and 8 a lot of host objects are objects and not functions. For example:

+ +
typeof alert === 'object'
+ +

Bakabilirsiniz

+ + diff --git "a/files/tr/web/javascript/reference/operat\303\266rler/arithmetic_operators/index.html" "b/files/tr/web/javascript/reference/operat\303\266rler/arithmetic_operators/index.html" deleted file mode 100644 index 04d337601d..0000000000 --- "a/files/tr/web/javascript/reference/operat\303\266rler/arithmetic_operators/index.html" +++ /dev/null @@ -1,294 +0,0 @@ ---- -title: Arithmetic operators -slug: Web/JavaScript/Reference/Operatörler/Arithmetic_Operators -tags: - - Aritmetik Operatörler - - JavaScript -translation_of: Web/JavaScript/Reference/Operators -translation_of_original: Web/JavaScript/Reference/Operators/Arithmetic_Operators ---- -
{{jsSidebar("Operators")}}
- -

Aritmetik operatörler sayısal değerleri (değişmez değerler veya değişkenler) kendi değişkeni olarak alır ve tek bir sayısal değer döndürür. Standart aritmetik operatörler toplama (+), çıkarma (-), çıkarma (*), ve bölme (/).

- -
{{EmbedInteractiveExample("pages/js/expressions-arithmetic.html")}}
- - - -

Toplama (+)

- -

Toplama işleci, sayısal değişkenlerin veya dize birleşiminin toplamını üretir.

- -

Syntax

- -
Operator: x + y
-
- -

Examples

- -
// Number + Number -> Toplama
-1 + 2 // 3
-
-// Boolean + Number -> Toplama
-true + 1 // 2
-
-// Boolean + Boolean -> Toplama
-false + false // 0
-
-// Number + String -> Birleşim
-5 + 'foo' // "5foo"
-
-// String + Boolean -> Birleşim
-'foo' + false // "foofalse"
-
-// String + String -> Birleşim
-'foo' + 'bar' // "foobar"
-
- -

Çıkarma (-)

- -

Çıkarma işleci (operator), iki değişkeni çıkarır ve farklarını üretir.

- -

Söz Dizimi

- -
Operator: x - y
-
- -

Örnekler

- -
5 - 3 // 2
-3 - 5 // -2
-'foo' - 3 // NaN(Sayı Değil)
- -

Bölme (/)

- -

Bölme operatörü, sol değişkenin bölüm olduğu ve sağ değişkenin bölen olduğu işlenenlerin bölümünü üretir.

- -

Söz Dizimi

- -
Operator: x / y
-
- -

Örnekler

- -
1 / 2      // 0.5 döndürür
-1 / 2      // Java''da 0 döndürür
-// (her iki sayı da açıkça kayan nokta sayısıdır)
-
-1.0 / 2.0  // JavaScript ve Java 0.5 döndürür
-
-2.0 / 0    // JavaScript sonsuz döndürür
-2.0 / 0.0  // Sonsuzu da döndürür
-2.0 / -0.0 // JavaScript eksi sonsuz da döndürür
- -

Çarpma (*)

- -

Çarpma operatörü değişkenlerin ürününü üretir.

- -

Söz Dizimi

- -
Operator: x * y
-
- -

Örnekler

- -
2 * 2 // 4
--2 * 2 // -4
-Infinity * 0 // NaN(Sayı Değil1)
-Infinity * Infinity // Sonsuz
-'foo' * 2 // NaN
-
- -

Kalan (%)

- -

Kalan operatörü, bir değişken ikinci bir değişken tarafından bölündüğünde kalan döndürür. Her zaman bölüm işareti alır.

- -

Söz Dizimi

- -
Operator: var1 % var2
-
- -

Örnekler

- -
12 % 5 // 2
--1 % 2 // -1
-1 % -2 // 1
-NaN % 2 // NaN
-1 % 2 // 1
-2 % 3 // 2
--4 % 2 // -0
-5.5 % 2 // 1.5
-
- -

Üs (**)

- -

The exponentiation operator returns the result of raising first operand to the power second operand. That is, var1var2, in the preceding statement, where var1 and var2 are variables. Exponentiation operator is right associative. a ** b ** c is equal to a ** (b ** c).

- -

Syntax

- -
Operator: var1 ** var2
-
- -

Notes

- -

In most languages like PHP and Python and others that have an exponentiation operator (**), the exponentiation operator is defined to have a higher precedence than unary operators such as unary + and unary -, but there are a few exceptions. For example, in Bash the ** operator is defined to have a lower precedence than unary operators. In JavaScript, it is impossible to write an ambiguous exponentiation expression, i.e. you cannot put a unary operator (+/-/~/!/delete/void/typeof) immediately before the base number.

- -
-2 ** 2;
-// 4 in Bash, -4 in other languages.
-// This is invalid in JavaScript, as the operation is ambiguous.
-
-
--(2 ** 2);
-// -4 in JavaScript and the author's intention is unambiguous.
-
- -

Examples

- -
2 ** 3 // 8
-3 ** 2 // 9
-3 ** 2.5 // 15.588457268119896
-10 ** -1 // 0.1
-NaN ** 2 // NaN
-
-2 ** 3 ** 2 // 512
-2 ** (3 ** 2) // 512
-(2 ** 3) ** 2 // 64
-
- -

To invert the sign of the result of an exponentiation expression:

- -
-(2 ** 2) // -4
-
- -

To force the base of an exponentiation expression to be a negative number:

- -
(-2) ** 2 // 4
-
- -
-

Note: JavaScript also has a bitwise operator ^ (logical XOR). ** and ^ are different (for example : 2 ** 3 === 8 when 2 ^ 3 === 1.)

-
- -

Artırma (++)

- -

Artış operatörü işlenenini artırır (bir ekler) ve bir değer döndürür.

- - - -

Söz Dizimi

- -
Operator: x++ yada ++x
-
- -

Örnekler

- -
// Postfix
-var x = 3;
-y = x++; // y = 3, x = 4
-
-// Prefix
-var a = 2;
-b = ++a; // a = 3, b = 3
-
- -

Azaltma (--)

- -

The decrement operator decrements (subtracts one from) its operand and returns a value.

- - - -

Syntax

- -
Operator: x-- or --x
-
- -

Examples

- -
// Postfix
-var x = 3;
-y = x--; // y = 3, x = 2
-
-// Prefix
-var a = 2;
-b = --a; // a = 1, b = 1
-
- -

Unary negation (-)

- -

The unary negation operator precedes its operand and negates it.

- -

Syntax

- -
Operator: -x
-
- -

Examples

- -
var x = 3;
-y = -x; // y = -3, x = 3
-
-// Unary negation operator can convert non-numbers into a number
-var x = "4";
-y = -x; // y = -4
-
- -

Unary plus (+)

- -

The unary plus operator precedes its operand and evaluates to its operand but attempts to convert it into a number, if it isn't already. Although unary negation (-) also can convert non-numbers, unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number. It can convert string representations of integers and floats, as well as the non-string values true, false, and null. Integers in both decimal and hexadecimal ("0x"-prefixed) formats are supported. Negative numbers are supported (though not for hex). If it cannot parse a particular value, it will evaluate to {{jsxref("NaN")}}.

- -

Syntax

- -
Operator: +x
-
- -

Examples

- -
+3     // 3
-+'3'   // 3
-+true  // 1
-+false // 0
-+null  // 0
-+function(val){ return val } // NaN
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-additive-operators', 'Additive operators')}}
{{SpecName('ESDraft', '#sec-postfix-expressions', 'Postfix expressions')}}
{{SpecName('ESDraft', '#sec-11.5', 'Multiplicative operators')}}
{{SpecName('ESDraft', '#sec-11.4', 'Unary operator')}}
- -

Browser compatibility

- - - -

{{Compat("javascript.operators.arithmetic")}}

- -

See also

- - diff --git "a/files/tr/web/javascript/reference/operat\303\266rler/bitwise_operators/index.html" "b/files/tr/web/javascript/reference/operat\303\266rler/bitwise_operators/index.html" deleted file mode 100644 index 410107226b..0000000000 --- "a/files/tr/web/javascript/reference/operat\303\266rler/bitwise_operators/index.html" +++ /dev/null @@ -1,565 +0,0 @@ ---- -title: Bitwise operators -slug: Web/JavaScript/Reference/Operatörler/Bitwise_Operators -translation_of: Web/JavaScript/Reference/Operators -translation_of_original: Web/JavaScript/Reference/Operators/Bitwise_Operators ---- -
{{jsSidebar("Operators")}}
- -

Bitsel işleçler işlediği elemanlara ondalık, onaltılık veya sayılar yerine 32 bit diziler(sıfır ve birler) olarak davranır. Örneğin, onluk bir sayı olan 9, ikilik sistemde 1001 ile gösterilir. Bitsel işleçler, işlemin iki tarafınada ikili değerleriyle işlem yapar ancak JavaScript standartı olan sayısal değerleri döner.

- -

Aşağıdaki tablo JavaScript'in bitsel işleçlerini özetler:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
OperatorUsageDescription
Bitwise ANDa & bBitsel işleçin iki tarafının karşılık gelen bitleri 1 ise, en az bir tanesi 0 ise 0 döndürür.
Bitwise ORa | bBitsel işleçin iki tarafının karşılık gelen bitlerinden en az biri 1 ise 1 döndürür.
Bitwise XORa ^ bBitsel işleçin iki tarafının karşılık gelen bitlerinden ancak bir tanesi 1 ise, 1 döndürür.
Bitwise NOT~ aİşlenenin bitlerini ters çevirir.
Left shifta << ba sayısının ikili haline, sağına b (< 32) adet bit 0 ekleyerek sola doğru kaydırır.
Sign-propagating right shifta >> ba sayısının ikili halini b (< 32) adet bit sağa kaydırır. Pozitif sayılar için b adet 0, negatif sayılar için 1 ekleyerek kaydırır.
Zero-fill right shifta >>> ba sayısının ikili gösterimine b (< 32) bit sağa kaydırır, a sayısının pozitif negatif olmasına bakmadan sayının soluna b adet 0 ekler.
- -

İşaretli 32-bit integer sayılar

- -

The operands of all bitwise operators are converted to signed 32-bit integers in two's complement format. Two's complement format means that a number's negative counterpart (e.g. 5 vs. -5) is all the number's bits inverted (bitwise NOT of the number, a.k.a. ones' complement of the number) plus one. For example, the following encodes the integer 314:

- -
00000000000000000000000100111010
-
- -

The following encodes ~314, i.e. the ones' complement of -314:

- -
11111111111111111111111011000101
-
- -

Finally, the following encodes -314, i.e. the two's complement of -314:

- -
11111111111111111111111011000110
-
- -

The two's complement guarantees that the left-most bit is 0 when the number is positive and 1 when the number is negative. Thus, it is called the sign bit.

- -

The number 0 is the integer that is composed completely of 0 bits.

- -
0 (base 10) = 00000000000000000000000000000000 (base 2)
-
- -

The number -1 is the integer that is composed completely of 1 bits.

- -
-1 (base 10) = 11111111111111111111111111111111 (base 2)
-
- -

The number -2147483648 (hexadecimal representation: -0x80000000) is the integer that is composed completely of 0 bits except the first (left-most) one.

- -
-2147483648 (base 10) = 10000000000000000000000000000000 (base 2)
-
- -

The number 2147483647 (hexadecimal representation: 0x7fffffff) is the integer that is composed completely of 1 bits except the first (left-most) one.

- -
2147483647 (base 10) = 01111111111111111111111111111111 (base 2)
-
- -

The numbers -2147483648 and 2147483647 are the minimum and the maximum integers representable through a 32bit signed number.

- -

Bitwise logical operators

- -

Conceptually, the bitwise logical operators work as follows:

- - - -

& (Bitwise AND)

- -

Performs the AND operation on each pair of bits. a AND b yields 1 only if both a and b are 1. The truth table for the AND operation is:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
aba AND b
000
010
100
111
- -
.    9 (base 10) = 00000000000000000000000000001001 (base 2)
-    14 (base 10) = 00000000000000000000000000001110 (base 2)
-                   --------------------------------
-14 & 9 (base 10) = 00000000000000000000000000001000 (base 2) = 8 (base 10)
-
- -

Bitwise ANDing any number x with 0 yields 0. Bitwise ANDing any number x with -1 yields x.

- -

| (Bitwise OR)

- -

Performs the OR operation on each pair of bits. a OR b yields 1 if either a or b is 1. The truth table for the OR operation is:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
aba OR b
000
011
101
111
- -
.    9 (base 10) = 00000000000000000000000000001001 (base 2)
-    14 (base 10) = 00000000000000000000000000001110 (base 2)
-                   --------------------------------
-14 | 9 (base 10) = 00000000000000000000000000001111 (base 2) = 15 (base 10)
-
- -

Bitwise ORing any number x with 0 yields x. Bitwise ORing any number x with -1 yields -1.

- -

^ (Bitwise XOR)

- -

Performs the XOR operation on each pair of bits. a XOR b yields 1 if a and b are different. The truth table for the XOR operation is:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
aba XOR b
000
011
101
110
- -
.    9 (base 10) = 00000000000000000000000000001001 (base 2)
-    14 (base 10) = 00000000000000000000000000001110 (base 2)
-                   --------------------------------
-14 ^ 9 (base 10) = 00000000000000000000000000000111 (base 2) = 7 (base 10)
-
- -

Bitwise XORing any number x with 0 yields x. Bitwise XORing any number x with -1 yields ~x.

- -

~ (Bitwise NOT)

- -

Performs the NOT operator on each bit. NOT a yields the inverted value (a.k.a. one's complement) of a. The truth table for the NOT operation is:

- - - - - - - - - - - - - - - - -
aNOT a
01
10
- -
 9 (base 10) = 00000000000000000000000000001001 (base 2)
-               --------------------------------
-~9 (base 10) = 11111111111111111111111111110110 (base 2) = -10 (base 10)
-
- -

Bitwise NOTing any number x yields -(x + 1). For example, ~-5 yields 4.

- -

Example with indexOf:

- -
var str = 'rawr';
-var searchFor = 'a';
-
-// this is alternative way of typing if (-1*str.indexOf('a') <= 0)
-if (~str.indexOf(searchFor)) {
-  // searchFor is in the string
-} else {
-  // searchFor is not in the string
-}
-
-// here are the values returned by (~str.indexOf(searchFor))
-// r == -1
-// a == -2
-// w == -3
-
- -

Bitwise shift operators

- -

The bitwise shift operators take two operands: the first is a quantity to be shifted, and the second specifies the number of bit positions by which the first operand is to be shifted. The direction of the shift operation is controlled by the operator used.

- -

Shift operators convert their operands to 32-bit integers in big-endian order and return a result of the same type as the left operand. The right operand should be less than 32, but if not only the low five bits will be used.

- -

<< (Left shift)

- -

This operator shifts the first operand the specified number of bits to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right.

- -

For example, 9 << 2 yields 36:

- -
.    9 (base 10): 00000000000000000000000000001001 (base 2)
-                  --------------------------------
-9 << 2 (base 10): 00000000000000000000000000100100 (base 2) = 36 (base 10)
-
- -

Bitwise shifting any number x to the left by y bits yields x * 2^y.

- -

>> (Sign-propagating right shift)

- -

This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Copies of the leftmost bit are shifted in from the left. Since the new leftmost bit has the same value as the previous leftmost bit, the sign bit (the leftmost bit) does not change. Hence the name "sign-propagating".

- -

For example, 9 >> 2 yields 2:

- -
.    9 (base 10): 00000000000000000000000000001001 (base 2)
-                  --------------------------------
-9 >> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)
-
- -

Likewise, -9 >> 2 yields -3, because the sign is preserved:

- -
.    -9 (base 10): 11111111111111111111111111110111 (base 2)
-                   --------------------------------
--9 >> 2 (base 10): 11111111111111111111111111111101 (base 2) = -3 (base 10)
-
- -

>>> (Zero-fill right shift)

- -

This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left. The sign bit becomes 0, so the result is always non-negative.

- -

For non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result. For example, 9 >>> 2 yields 2, the same as 9 >> 2:

- -
.     9 (base 10): 00000000000000000000000000001001 (base 2)
-                   --------------------------------
-9 >>> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)
-
- -

However, this is not the case for negative numbers. For example, -9 >>> 2 yields 1073741821, which is different than -9 >> 2 (which yields -3):

- -
.     -9 (base 10): 11111111111111111111111111110111 (base 2)
-                    --------------------------------
--9 >>> 2 (base 10): 00111111111111111111111111111101 (base 2) = 1073741821 (base 10)
-
- -

Examples

- -

Flags and bitmasks

- -

The bitwise logical operators are often used to create, manipulate, and read sequences of flags, which are like binary variables. Variables could be used instead of these sequences, but binary flags take much less memory (by a factor of 32).

- -

Suppose there are 4 flags:

- - - -

These flags are represented by a sequence of bits: DCBA. When a flag is set, it has a value of 1. When a flag is cleared, it has a value of 0. Suppose a variable flags has the binary value 0101:

- -
var flags = 5;   // binary 0101
-
- -

This value indicates:

- - - -

Since bitwise operators are 32-bit, 0101 is actually 00000000000000000000000000000101, but the preceding zeroes can be neglected since they contain no meaningful information.

- -

A bitmask is a sequence of bits that can manipulate and/or read flags. Typically, a "primitive" bitmask for each flag is defined:

- -
var FLAG_A = 1; // 0001
-var FLAG_B = 2; // 0010
-var FLAG_C = 4; // 0100
-var FLAG_D = 8; // 1000
-
- -

New bitmasks can be created by using the bitwise logical operators on these primitive bitmasks. For example, the bitmask 1011 can be created by ORing FLAG_A, FLAG_B, and FLAG_D:

- -
var mask = FLAG_A | FLAG_B | FLAG_D; // 0001 | 0010 | 1000 => 1011
-
- -

Individual flag values can be extracted by ANDing them with a bitmask, where each bit with the value of one will "extract" the corresponding flag. The bitmask masks out the non-relevant flags by ANDing with zeroes (hence the term "bitmask"). For example, the bitmask 0100 can be used to see if flag C is set:

- -
// if we own a cat
-if (flags & FLAG_C) { // 0101 & 0100 => 0100 => true
-   // do stuff
-}
-
- -

A bitmask with multiple set flags acts like an "either/or". For example, the following two are equivalent:

- -
// if we own a bat or we own a cat
-// (0101 & 0010) || (0101 & 0100) => 0000 || 0100 => true
-if ((flags & FLAG_B) || (flags & FLAG_C)) {
-   // do stuff
-}
-
- -
// if we own a bat or cat
-var mask = FLAG_B | FLAG_C; // 0010 | 0100 => 0110
-if (flags & mask) { // 0101 & 0110 => 0100 => true
-   // do stuff
-}
-
- -

Flags can be set by ORing them with a bitmask, where each bit with the value one will set the corresponding flag, if that flag isn't already set. For example, the bitmask 1100 can be used to set flags C and D:

- -
// yes, we own a cat and a duck
-var mask = FLAG_C | FLAG_D; // 0100 | 1000 => 1100
-flags |= mask;   // 0101 | 1100 => 1101
-
- -

Flags can be cleared by ANDing them with a bitmask, where each bit with the value zero will clear the corresponding flag, if it isn't already cleared. This bitmask can be created by NOTing primitive bitmasks. For example, the bitmask 1010 can be used to clear flags A and C:

- -
// no, we don't have an ant problem or own a cat
-var mask = ~(FLAG_A | FLAG_C); // ~0101 => 1010
-flags &= mask;   // 1101 & 1010 => 1000
-
- -

The mask could also have been created with ~FLAG_A & ~FLAG_C (De Morgan's law):

- -
// no, we don't have an ant problem, and we don't own a cat
-var mask = ~FLAG_A & ~FLAG_C;
-flags &= mask;   // 1101 & 1010 => 1000
-
- -

Flags can be toggled by XORing them with a bitmask, where each bit with the value one will toggle the corresponding flag. For example, the bitmask 0110 can be used to toggle flags B and C:

- -
// if we didn't have a bat, we have one now,
-// and if we did have one, bye-bye bat
-// same thing for cats
-var mask = FLAG_B | FLAG_C;
-flags = flags ^ mask;   // 1100 ^ 0110 => 1010
-
- -

Finally, the flags can all be flipped with the NOT operator:

- -
// entering parallel universe...
-flags = ~flags;    // ~1010 => 0101
-
- -

Conversion snippets

- -

Convert a binary String to a decimal Number:

- -
var sBinString = '1011';
-var nMyNumber = parseInt(sBinString, 2);
-alert(nMyNumber); // prints 11, i.e. 1011
-
- -

Convert a decimal Number to a binary String:

- -
var nMyNumber = 11;
-var sBinString = nMyNumber.toString(2);
-alert(sBinString); // prints 1011, i.e. 11
-
- -

Automate Mask Creation

- -

You can create multiple masks from a set of Boolean values, like this:

- -
function createMask() {
-  var nMask = 0, nFlag = 0, nLen = arguments.length > 32 ? 32 : arguments.length;
-  for (nFlag; nFlag < nLen; nMask |= arguments[nFlag] << nFlag++);
-  return nMask;
-}
-var mask1 = createMask(true, true, false, true); // 11, i.e.: 1011
-var mask2 = createMask(false, false, true); // 4, i.e.: 0100
-var mask3 = createMask(true); // 1, i.e.: 0001
-// etc.
-
-alert(mask1); // prints 11, i.e.: 1011
-
- -

Reverse algorithm: an array of booleans from a mask

- -

If you want to create an Array of Booleans from a mask you can use this code:

- -
function arrayFromMask(nMask) {
-  // nMask must be between -2147483648 and 2147483647
-  if (nMask > 0x7fffffff || nMask < -0x80000000) {
-    throw new TypeError('arrayFromMask - out of range');
-  }
-  for (var nShifted = nMask, aFromMask = []; nShifted;
-       aFromMask.push(Boolean(nShifted & 1)), nShifted >>>= 1);
-  return aFromMask;
-}
-
-var array1 = arrayFromMask(11);
-var array2 = arrayFromMask(4);
-var array3 = arrayFromMask(1);
-
-alert('[' + array1.join(', ') + ']');
-// prints "[true, true, false, true]", i.e.: 11, i.e.: 1011
-
- -

You can test both algorithms at the same time…

- -
var nTest = 19; // our custom mask
-var nResult = createMask.apply(this, arrayFromMask(nTest));
-
-alert(nResult); // 19
-
- -

For didactic purpose only (since there is the Number.toString(2) method), we show how it is possible to modify the arrayFromMask algorithm in order to create a String containing the binary representation of a Number, rather than an Array of Booleans:

- -
function createBinaryString(nMask) {
-  // nMask must be between -2147483648 and 2147483647
-  for (var nFlag = 0, nShifted = nMask, sMask = ''; nFlag < 32;
-       nFlag++, sMask += String(nShifted >>> 31), nShifted <<= 1);
-  return sMask;
-}
-
-var string1 = createBinaryString(11);
-var string2 = createBinaryString(4);
-var string3 = createBinaryString(1);
-
-alert(string1);
-// prints 00000000000000000000000000001011, i.e. 11
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-11.7')}}{{Spec2('ES5.1')}}Defined in several sections of the specification: Bitwise NOT operator, Bitwise shift operators, Binary bitwise operators
{{SpecName('ES6', '#sec-bitwise-shift-operators')}}{{Spec2('ES6')}}Defined in several sections of the specification: Bitwise NOT operator, Bitwise shift operators, Binary bitwise operators
{{SpecName('ESDraft', '#sec-bitwise-shift-operators')}}{{Spec2('ESDraft')}}Defined in several sections of the specification: Bitwise NOT operator, Bitwise shift operators, Binary bitwise operators
- -

Browser compatibility

- - - -

{{Compat("javascript.operators.bitwise")}}

- -

See also

- - diff --git "a/files/tr/web/javascript/reference/operat\303\266rler/function_star_/index.html" "b/files/tr/web/javascript/reference/operat\303\266rler/function_star_/index.html" deleted file mode 100644 index 193e00f205..0000000000 --- "a/files/tr/web/javascript/reference/operat\303\266rler/function_star_/index.html" +++ /dev/null @@ -1,84 +0,0 @@ ---- -title: function* expression -slug: Web/JavaScript/Reference/Operatörler/function* -translation_of: Web/JavaScript/Reference/Operators/function* ---- -
{{jsSidebar("Operators")}}
- -

The function* keyword can be used to define a generator function inside an expression.

- -
{{EmbedInteractiveExample("pages/js/expressions-functionasteriskexpression.html")}}
- - - -

Syntax

- -
function* [name]([param1[, param2[, ..., paramN]]]) {
-   statements
-}
- -

Parametreler

- -
-
name
-
The function name. Can be omitted, in which case the function is anonymous. The name is only local to the function body.
-
paramN
-
Argüman adıdır, bir fonksiyon maxiumum 255 argüman alır.
-
statements
-
Fonksiyon kodları.
-
- -

Açıklama

- -

A function* expression is very similar to and has almost the same syntax as a {{jsxref('Statements/function*', 'function* statement')}}. The main difference between a function* expression and a function* statement is the function name, which can be omitted in function* expressions to create anonymous generator functions. See also the chapter about functions for more information.

- -

Örnekler

- -

Aşağıdaki adlandırılmamış fonksiyondur ve gelen değer karesini verir.

- -
var x = function*(y) {
-   yield y * y;
-};
-
- -

Özellikler

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#', 'function*')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#', 'function*')}}{{Spec2('ESDraft')}} 
- -

Tarayıcı uyumluluğu

- - - -

{{Compat("javascript.operators.function_star")}}

- -

Bakabilirsiniz

- - diff --git "a/files/tr/web/javascript/reference/operat\303\266rler/index.html" "b/files/tr/web/javascript/reference/operat\303\266rler/index.html" deleted file mode 100644 index f42305b092..0000000000 --- "a/files/tr/web/javascript/reference/operat\303\266rler/index.html" +++ /dev/null @@ -1,277 +0,0 @@ ---- -title: İfadeler ve operatörler -slug: Web/JavaScript/Reference/Operatörler -translation_of: Web/JavaScript/Reference/Operators ---- -
{{jsSidebar("Operators")}}
- -

Bu döküman bütün JavaScript ifadelerini,operatörlerini ve anahtar kelimeleri içerir.

- -

Expressions and operators by category

- -

For an alphabetical listing see the sidebar on the left.

- -

Birincil İfadeler

- -

Genel İfadeler ve basit anahtar kelimeler.

- -
-
{{jsxref("Operators/this", "this")}}
-
The this keyword refers to the function's execution context.
-
{{jsxref("Operators/function", "function")}}
-
The function keyword defines a function expression.
-
{{experimental_inline}} {{jsxref("Operators/class", "class")}}
-
The class keyword defines a class expression.
-
{{experimental_inline}} {{jsxref("Operators/function*", "function*")}}
-
The function* keyword defines a generator function expression.
-
{{experimental_inline}} {{jsxref("Operators/yield", "yield")}}
-
Pause and resume a generator function
-
{{experimental_inline}} {{jsxref("Operators/yield*", "yield*")}}
-
Delegate to another generator function or iterable object.
-
{{jsxref("Global_Objects/Array", "[]")}}
-
Array initializer/literal syntax.
-
{{jsxref("Operators/Object_initializer", "{}")}}
-
Object initializer/literal syntax.
-
{{jsxref("Global_Objects/RegExp", "/ab+c/i")}}
-
Regular expression literal syntax.
-
{{experimental_inline}} {{jsxref("Operators/Array_comprehensions", "[for (x of y) x]")}}
-
Array comprehensions.
-
{{experimental_inline}} {{jsxref("Operators/Generator_comprehensions", "(for (x of y) y)")}}
-
Generator comprehensions.
-
{{jsxref("Operators/Grouping", "( )")}}
-
Grouping operator.
-
- -

Left-hand-side expressions

- -

Left values are the destination of an assignment.

- -
-
{{jsxref("Operators/Property_accessors", "Property accessors", "", 1)}}
-
Member operators provide access to a property or method of an object
- (object.property and object["property"]).
-
{{jsxref("Operators/new", "new")}}
-
The new operator creates an instance of a constructor.
-
{{experimental_inline}} {{jsxref("Operators/super", "super")}}
-
The super keyword calls the parent constructor.
-
{{experimental_inline}} {{jsxref("Operators/Spread_operator", "...obj")}}
-
The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.
-
- -

Increment and decrement

- -

Postfix/prefix increment and postfix/prefix decrement operators.

- -
-
{{jsxref("Operators/Arithmetic_Operators", "A++", "#Increment")}}
-
Postfix increment operator.
-
{{jsxref("Operators/Arithmetic_Operators", "A--", "#Decrement")}}
-
Postfix decrement operator.
-
{{jsxref("Operators/Arithmetic_Operators", "++A", "#Increment")}}
-
Prefix increment operator.
-
{{jsxref("Operators/Arithmetic_Operators", "--A", "#Decrement")}}
-
Prefix decrement operator.
-
- -

Unary operators

- -

A unary operation is operation with only one operand.

- -
-
{{jsxref("Operators/delete", "delete")}}
-
The delete operator deletes a property from an object.
-
{{jsxref("Operators/void", "void")}}
-
The void operator discards an expression's return value.
-
{{jsxref("Operators/typeof", "typeof")}}
-
The typeof operator determines the type of a given object.
-
{{jsxref("Operators/Arithmetic_Operators", "+", "#Unary_plus")}}
-
The unary plus operator converts its operand to Number type.
-
{{jsxref("Operators/Arithmetic_Operators", "-", "#Unary_negation")}}
-
The unary negation operator converts its operand to Number type and then negates it.
-
{{jsxref("Operators/Bitwise_Operators", "~", "#Bitwise_NOT")}}
-
Bitwise NOT operator.
-
{{jsxref("Operators/Logical_Operators", "!", "#Logical_NOT")}}
-
Logical NOT operator.
-
- -

Arithmetic operators

- -

Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value.

- -
-
{{jsxref("Operators/Arithmetic_Operators", "+", "#Addition")}}
-
Addition operator.
-
{{jsxref("Operators/Arithmetic_Operators", "-", "#Subtraction")}}
-
Subtraction operator.
-
{{jsxref("Operators/Arithmetic_Operators", "/", "#Division")}}
-
Division operator.
-
{{jsxref("Operators/Arithmetic_Operators", "*", "#Multiplication")}}
-
Multiplication operator.
-
{{jsxref("Operators/Arithmetic_Operators", "%", "#Remainder")}}
-
Remainder operator.
-
- -

Relational operators

- -

A comparison operator compares its operands and returns a Boolean value based on whether the comparison is true.

- -
-
{{jsxref("Operators/in", "in")}}
-
The in operator determines whether an object has a given property.
-
{{jsxref("Operators/instanceof", "instanceof")}}
-
The instanceof operator determines whether an object is an instance of another object.
-
{{jsxref("Operators/Comparison_Operators", "<", "#Less_than_operator")}}
-
Less than operator.
-
{{jsxref("Operators/Comparison_Operators", ">", "#Greater_than_operator")}}
-
Greater than operator.
-
{{jsxref("Operators/Comparison_Operators", "<=", "#Less_than_or_equal_operator")}}
-
Less than or equal operator.
-
{{jsxref("Operators/Comparison_Operators", ">=", "#Greater_than_or_equal_operator")}}
-
Greater than or equal operator.
-
- -

Equality operators

- -

The result of evaluating an equality operator is always of type Boolean based on whether the comparison is true.

- -
-
{{jsxref("Operators/Comparison_Operators", "==", "#Equality")}}
-
Equality operator.
-
{{jsxref("Operators/Comparison_Operators", "!=", "#Inequality")}}
-
Inequality operator.
-
{{jsxref("Operators/Comparison_Operators", "===", "#Identity")}}
-
Identity operator.
-
{{jsxref("Operators/Comparison_Operators", "!==", "#Nonidentity")}}
-
Nonidentity operator.
-
- -

Bitwise shift operators

- -

Operations to shift all bits of the operand.

- -
-
{{jsxref("Operators/Bitwise_Operators", "<<", "#Left_shift")}}
-
Bitwise left shift operator.
-
{{jsxref("Operators/Bitwise_Operators", ">>", "#Right_shift")}}
-
Bitwise right shift operator.
-
{{jsxref("Operators/Bitwise_Operators", ">>>", "#Unsigned_right_shift")}}
-
Bitwise unsigned right shift operator.
-
- -

Binary bitwise operators

- -

Bitwise operators treat their operands as a set of 32 bits (zeros and ones) and return standard JavaScript numerical values.

- -
-
{{jsxref("Operators/Bitwise_Operators", "&", "#Bitwise_AND")}}
-
Bitwise AND.
-
{{jsxref("Operators/Bitwise_Operators", "|", "#Bitwise_OR")}}
-
Bitwise OR.
-
{{jsxref("Operators/Bitwise_Operators", "^", "#Bitwise_XOR")}}
-
Bitwise XOR.
-
- -

Binary logical operators

- -

Logical operators are typically used with boolean (logical) values, and when they are, they return a boolean value.

- -
-
{{jsxref("Operators/Logical_Operators", "&&", "#Logical_AND")}}
-
Logical AND.
-
{{jsxref("Operators/Logical_Operators", "||", "#Logical_OR")}}
-
Logical OR.
-
- -

Conditional (ternary) operator

- -
-
{{jsxref("Operators/Conditional_Operator", "(condition ? ifTrue : ifFalse)")}}
-
-

The conditional operator returns one of two values based on the logical value of the condition.

-
-
- -

Assignment operators

- -

An assignment operator assigns a value to its left operand based on the value of its right operand.

- -
-
{{jsxref("Operators/Assignment_Operators", "=", "#Assignment")}}
-
Assignment operator.
-
{{jsxref("Operators/Assignment_Operators", "*=", "#Multiplication_assignment")}}
-
Multiplication assignment.
-
{{jsxref("Operators/Assignment_Operators", "/=", "#Division_assignment")}}
-
Division assignment.
-
{{jsxref("Operators/Assignment_Operators", "%=", "#Remainder_assignment")}}
-
Remainder assignment.
-
{{jsxref("Operators/Assignment_Operators", "+=", "#Addition_assignment")}}
-
Addition assignment.
-
{{jsxref("Operators/Assignment_Operators", "-=", "#Subtraction_assignment")}}
-
Subtraction assignment
-
{{jsxref("Operators/Assignment_Operators", "<<=", "#Left_shift_assignment")}}
-
Left shift assignment.
-
{{jsxref("Operators/Assignment_Operators", ">>=", "#Right_shift_assignment")}}
-
Right shift assignment.
-
{{jsxref("Operators/Assignment_Operators", ">>>=", "#Unsigned_right_shift_assignment")}}
-
Unsigned right shift assignment.
-
{{jsxref("Operators/Assignment_Operators", "&=", "#Bitwise_AND_assignment")}}
-
Bitwise AND assignment.
-
{{jsxref("Operators/Assignment_Operators", "^=", "#Bitwise_XOR_assignment")}}
-
Bitwise XOR assignment.
-
{{jsxref("Operators/Assignment_Operators", "|=", "#Bitwise_OR_assignment")}}
-
Bitwise OR assignment.
-
{{experimental_inline}} {{jsxref("Operators/Destructuring_assignment", "[a, b] = [1, 2]")}}
- {{experimental_inline}} {{jsxref("Operators/Destructuring_assignment", "{a, b} = {a:1, b:2}")}}
-
-

Destructuring assignment allows you to assign the properties of an array or object to variables using syntax that looks similar to array or object literals.

-
-
- -

Comma operator

- -
-
{{jsxref("Operators/Comma_Operator", ",")}}
-
The comma operator allows multiple expressions to be evaluated in a single statement and returns the result of the last expression.
-
- -

Non-standard features

- -
-
{{non-standard_inline}} {{jsxref("Operators/Legacy_generator_function", "Legacy generator function", "", 1)}}
-
The function keyword can be used to define a legacy generator function inside an expression. To make the function a legacy generator, the function body should contains at least one {{jsxref("Operators/yield", "yield")}} expression.
-
{{non-standard_inline}} {{jsxref("Operators/Expression_closures", "Expression closures", "", 1)}}
-
The expression closure syntax is a shorthand for writing simple function.
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
ECMAScript 1st Edition.StandardInitial definition.
{{SpecName('ES5.1', '#sec-11', 'Expressions')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}{{Spec2('ES6')}}New: Spread operator, destructuring assignment, super keyword, Array comprehensions, Generator comprehensions
- -

See also

- - diff --git "a/files/tr/web/javascript/reference/operat\303\266rler/instanceof/index.html" "b/files/tr/web/javascript/reference/operat\303\266rler/instanceof/index.html" deleted file mode 100644 index 3434ea34b9..0000000000 --- "a/files/tr/web/javascript/reference/operat\303\266rler/instanceof/index.html" +++ /dev/null @@ -1,207 +0,0 @@ ---- -title: instanceof -slug: Web/JavaScript/Reference/Operatörler/instanceof -translation_of: Web/JavaScript/Reference/Operators/instanceof ---- -
{{jsSidebar("Operators")}}
- -

Instanceof operatorü bir nesne'nin prototip (prototype) zincirinin, belirli bir prototipin kurucu(constructor) metodu olup olmadığını testeder.

- -

Syntax

- -
object instanceof constructor
- -

Parametreler

- -
-
object
-
Test edilecek nesne
-
- -
-
constructor
-
Test edilecek karşı kurucu fonksiyon
-
- -

Açıklama

- -

Instanceof operatorü nesnenin prototip zincirinde 'constructor.prototype' varlığını testeder.

- -
// defining constructors
-function C() {}
-function D() {}
-
-var o = new C();
-
-// true, because: Object.getPrototypeOf(o) === C.prototype
-o instanceof C;
-
-// false, because D.prototype is nowhere in o's prototype chain
-o instanceof D;
-
-o instanceof Object; // true, because:
-C.prototype instanceof Object // true
-
-C.prototype = {};
-var o2 = new C();
-
-o2 instanceof C; // true
-
-// false, because C.prototype is nowhere in
-// o's prototype chain anymore
-o instanceof C;
-
-D.prototype = new C(); // add C to [[Prototype]] linkage of D
-var o3 = new D();
-o3 instanceof D; // true
-o3 instanceof C; // true since C.prototype is now in o3's prototype chain
-
- -

Bir instanceof testinin değerinin yapıcıların prototip özelliklerinde yapılan değişikliklere göre değişebileceğini ve Object.setPrototypeOf kullanılarak bir nesne prototipini değiştirerek de değişebileceğini unutmayın. Standart olmayan __proto__ sözde-özelliği(pseudo-property) kullanarak da mümkündür.

- -

instanceof ve çoklu bağlam (multiple context) (e.g. frames or windows)

- -

Farklı kapsamların (Scopes) farklı yürütme (execution) ortamları vardır. Bu, farklı yerleşik yapılara sahip oldukları anlamına gelir (farklı global nesne, farklı yapıcılar, vb.). Bu, beklenmedik sonuçlara neden olabilir. Örneğin, [] instanceof window.frames [0] .Array false döndürür, çünkü Array.prototype! == window.frames [0] .Array ve diziler belli bir dizgeden (former) miras alırlar. Bu başlangıçta mantıklı gelmeyebilir, ancak betiğinizde (script) birden çok cerceve (frame) veya pencereyi (window) ele almaya başladığınızda ve nesneleri fonsiyonlarla bir bağlamdan diğerine geçirirken, bu geçerli ve güçlü bir sayı olacaktır. Örneğin, belirli bir nesnenin aslında Array.isArray (myObj) kullanarak bir Array olup olmadığını güvenli bir şekilde kontrol edebilirsiniz.

- -
Mozilla geliştiricleri için not: - -

Kodda XPCOM kullanımının özel bir etkisi vardır: obj instanceof xpcomInterface (ör. Components.interfaces.nsIFile), obj.QueryInterface (xpcomInterface) çağırır ve QueryInterface başarılı olursa true değerini döndürür. Bu tür bir aramanın bir yan etkisi, başarılı bir örnekleme sonucunda obj'de xpcomInterface özelliklerini kullanabilmenizdir. Standart JavaScript globals'ın aksine, test obj instance of xpcomInterface, obj farklı bir kapsamdan olsa bile beklendiği gibi çalışır.

-
- -

Examples

- -

Demonstrating that String and Date are of type Object and exceptional cases

- -

The following code uses instanceof to demonstrate that String and Date objects are also of type Object (they are derived from Object).

- -

However, objects created with the object literal notation are an exception here: Although the prototype is undefined, instanceof Object returns true.

- -
var simpleStr = 'This is a simple string';
-var myString  = new String();
-var newStr    = new String('String created with constructor');
-var myDate    = new Date();
-var myObj     = {};
-
-simpleStr instanceof String; // returns false, checks the prototype chain, finds undefined
-myString  instanceof String; // returns true
-newStr    instanceof String; // returns true
-myString  instanceof Object; // returns true
-
-myObj instanceof Object;    // returns true, despite an undefined prototype
-({})  instanceof Object;    // returns true, same case as above
-
-myString instanceof Date;   // returns false
-
-myDate instanceof Date;     // returns true
-myDate instanceof Object;   // returns true
-myDate instanceof String;   // returns false
-
- -

Demonstrating that mycar is of type Car and type Object

- -

The following code creates an object type Car and an instance of that object type, mycar. The instanceof operator demonstrates that the mycar object is of type Car and of type Object.

- -
function Car(make, model, year) {
-  this.make = make;
-  this.model = model;
-  this.year = year;
-}
-var mycar = new Car('Honda', 'Accord', 1998);
-var a = mycar instanceof Car;    // returns true
-var b = mycar instanceof Object; // returns true
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-relational-operators', 'Relational Operators')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-relational-operators', 'Relational Operators')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.8.6', 'The instanceof operator')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-11.8.6', 'The instanceof operator')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.4.
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

See also

- - diff --git "a/files/tr/web/javascript/reference/operat\303\266rler/mantiksal_operatorler/index.html" "b/files/tr/web/javascript/reference/operat\303\266rler/mantiksal_operatorler/index.html" deleted file mode 100644 index 8a1e2ea56f..0000000000 --- "a/files/tr/web/javascript/reference/operat\303\266rler/mantiksal_operatorler/index.html" +++ /dev/null @@ -1,312 +0,0 @@ ---- -title: Mantıksal Operatörler -slug: Web/JavaScript/Reference/Operatörler/Mantiksal_Operatorler -tags: - - Değil - - JavaScript - - Mantıksal Operatörler - - Operator - - Referans - - ve - - ya da -translation_of: Web/JavaScript/Reference/Operators -translation_of_original: Web/JavaScript/Reference/Operators/Logical_Operators ---- -
{{jsSidebar("Operators")}}
- -

Mantıksal operatörler genellikle {{jsxref("Boolean")}} (mantıksal) değerleri ile kullanılır. Kullanıldıklarında, bir boolean değer döndürürler. Ancak, && ve || operatörleri aslında belirtilmiş olan operandlardan birinin değerini döndürür, bu sebeple eğer bu operatörler Boolean olmayan değerler ile kullanılırsa, Boolean olmayan değerler üretebilirler.

- -

Açıklama

- -

Mantıksal operatörler aşağıdaki tabloda açıklanıyor:

- - - - - - - - - - - - - - - - - - - - - - - - -
OperatörKullanımAçıklama
Mantıksal VE (&&)expr1 && expr2Eğer expr1 false değerine dönüştürülebilirse, expr1  döndürülür. Aksi halde, expr2 döndürülür. Böylece, Boolean değerleri ile kullanıldıklarında, && her iki operand true ise true ; aksi halde, false döndürür.
Mantıksal YA DA (||)expr1 || expr2Eğer expr1 true değerine dönüştürülebilirse, expr1 döndürülür, aksi halde, expr2 döndürülür. Böylece, Boolean değerleri ile kullanıldıklarında, || her iki operanddan herhangi biri true ise true döndürür.
Mantıksal DEĞİL (!)!exprEğer operandın değeri true is false döndürür, aksi alde true döndürür.
- -

Eğer bir değer true değerine dönüştürülebiliyorsa, ona {{Glossary("truthy")}} ismi verilir. Eğer bir değer false değerine dönüştürülebiliyorsa, ona {{Glossary("falsy")}} denir.

- -

False değerine dönüştürülebilen ifadelere örnekler:

- - - -

&& ve || operatörleri Boolean olmayan değerler ile kullanılabiliyor olmasına rağmen, döndürdükleri değerler her zaman Boolean değerlerine çevirilebildiğinden, halen Boolean operatörleri olarak düşünülebilirler.

- -

Kısa-devre değerlendirmeleri

- -

Mantıksal operatörler soldan sağa çalıştırıldıkları gibi, mümkünse aşağıdaki kurallar kullanılarak "kısa devre" testine tabi tutulurlar:

- - - -

Mantık kuralları bu değerlendirmelerin doğruluğunu garantiler. Yukarıdaki ifadelerin tümünün çalıştırılmayacağına, bu sebeple hepsinin yan etkisinin olmayacağına dikkat edin. Ayrıca yukarıdaki ifadenin (herhangi) kısmının tamamıyla bir mantıksal ifadeye eşit olduğuna dikkat edin. (parantezler ile gösterildiği gibi).

- -

Örneğin, aşağıdaki iki fonksiyon birbirinin aynısıdır.

- -
function shortCircuitEvaluation() {
-  doSomething() || doSomethingElse()
-}
-
-function equivalentEvaluation() {
-  var flag = doSomething();
-  if (!flag) {
-    doSomethingElse();
-  }
-}
-
- -

Ancak, aşağıdaki ifadeler operatör önceliğine göre eşit değildir ve sağ el operatörünün tek bir ifade olmasının önemini vurgular (gerekirse parantezler ile gruplanır).

- -
false && true  || true      // returns true
-false && (true || true)     // returns false
- -

Mantıksal VE (&&)

- -

Aşağıdaki kod && (mantıksal VE) operatörüyle ilgili örnekleri gösterir.

- -
a1 = true  && true      // t && t returns true
-a2 = true  && false     // t && f returns false
-a3 = false && true      // f && t returns false
-a4 = false && (3 == 4)  // f && f returns false
-a5 = "Cat" && "Dog"     // t && t returns "Dog"
-a6 = false && "Cat"     // f && t returns false
-a7 = "Cat" && false     // t && f returns false
-a8 = "" && false        // returns ""
-a9 = false && ||        // returns false
-
- -

Mantıksal YA DA (||)

- -

Aşağıdaki kod || (mantıksal YA DA) operatörüyle ilgili örnekleri gösterir.

- -
o1 = true  || true       // t || t returns true
-o2 = false || true       // f || t returns true
-o3 = true  || false      // t || f returns true
-o4 = false || (3 == 4)   // f || f returns false
-o5 = "Cat" || "Dog"      // t || t returns "Cat"
-o6 = false || "Cat"      // f || t returns "Cat"
-o7 = "Cat" || false      // t || f returns "Cat"
-o8 = ""    || false      // returns false
-o9 = false || ""         // returns ""
-
- -

Mantıksal DEĞİL (!)

- -

Aşağıdaki kod ! (mantıksal DEĞİL) operatörüyle ilgili örnekleri gösterir.

- -
n1 = !true              // !t returns false
-n2 = !false             // !f returns true
-n3 = !"Cat"             // !t returns false
-
- -

Dönüşüm kuralları

- -

VE operatörünü YA DA operatörüne dönüştürmek

- -

Booleanları içeren aşağıdaki ifade:

- -
bCondition1 && bCondition2
- -

her zaman şuna eşittir:

- -
!(!bCondition1 || !bCondition2)
- -

YA DA operatörünü VE operatörüne çevirmek

- -

Booleanları içeren aşağıdaki ifade:

- -
bCondition1 || bCondition2
- -

her zaman şuna eşittir:

- -
!(!bCondition1 && !bCondition2)
- -

DEĞİL operatörleri arasında dönüşüm yapmak

- -

Booleanları içeren aşağıdaki ifade:

- -
!!bCondition
- -

her zaman şuna eşittir: 

- -
bCondition
- -

İç içe geçmiş parantezleri kaldırmak

- -

Mantıksal operatörlerin soldan sağa değerlendirilmesi durumunda, kompleks bir ifadeden parantezleri bazı kuralları takip ederek kaldırmak mümkündür.

- -

İç içe geçmiş VE operatörünü kaldırmak

- -

Aşağıda, Boolean içeren bu bileşik işlem:

- -
bCondition1 || (bCondition2 && bCondition3)
- -

her zaman şuna eşittir:

- -
bCondition1 || bCondition2 && bCondition3
- -

İç içe geçmiş YA DA operatörünü kaldırmak

- -

Aşağıda, Boolean içeren bu bileşik ifade:

- -
bCondition1 && (bCondition2 || bCondition3)
- -

her zaman şuna eşittir:

- -
!(!bCondition1 || !bCondition2 && !bCondition3)
- -

Özellikler

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ÖzellikDurumAçıklama
{{SpecName('ES1')}}{{Spec2('ES1')}}İlk tanım.
{{SpecName('ES5.1', '#sec-11.11')}}{{Spec2('ES5.1')}}Tarifnamenin birkaç bölümünde tanımlandı: Logical NOT Operator, Binary Logical Operators
{{SpecName('ES6', '#sec-binary-logical-operators')}}{{Spec2('ES6')}}Tarifnamenin birkaç bölümünde tanımlandı: Logical NOT Operator, Binary Logical Operators
{{SpecName('ESDraft', '#sec-binary-logical-operators')}}{{Spec2('ESDraft')}}Tarifnamenin birkaç bölümünde tanımlandı: Logical NOT Operator, Binary Logical Operators
- -

Tarayıcı Uyumluluğu

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Mantıksal VE (&&){{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-

Mantıksal YA DA (||)

-
{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Mantıksal DEĞİL (!){{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ÖzellikAndroidAndroid üzerinde ChromeFirefox Mobil (Gecko)IE MobilOpera MobilSafari Mobil
Logical AND (&&){{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Logical OR (||){{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Logical NOT (!){{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Ayrıca bakın

- - diff --git "a/files/tr/web/javascript/reference/operat\303\266rler/super/index.html" "b/files/tr/web/javascript/reference/operat\303\266rler/super/index.html" deleted file mode 100644 index 3dd3f62ebf..0000000000 --- "a/files/tr/web/javascript/reference/operat\303\266rler/super/index.html" +++ /dev/null @@ -1,165 +0,0 @@ ---- -title: super -slug: Web/JavaScript/Reference/Operatörler/super -translation_of: Web/JavaScript/Reference/Operators/super ---- -
{{jsSidebar("Operators")}}
- -

super, ebeveyn sınıftaki fonksiyonlara ulaşmak ve onları çağırmak için kullanılan bir ifadedir.

- -

The super.prop and super[expr] expressions are valid in any method definition in both classes and object literals.

- -

Sözdizimi (Syntax)

- -
super([arguments]); // ebeveyn sınıfın constructot'ını çağırır.
-super.functionOnParent([arguments]); // ebeveyn sınıftaki functionOnParent fonksiyonunu çalıştırır.
-
- -

Açıklama

- -

Constructor içinde super ifadesi tek başına kullanılır ve this ifadesinden önce kullanılması zorunludur. Aynı zamanda super ifadesi ebeveyn sınıftaki fonksiyonları çağırmak için de kullanılabilir.

- -

Örnekler

- -

Sınflarda super kullanımı

- -

This code snippet is taken from the classes sample (live demo). Here super() is called to avoid duplicating the constructor parts' that are common between Rectangle and Square.

- -
class Rectangle {
-  constructor(height, width) {
-    this.name = 'Rectangle';
-    this.height = height;
-    this.width = width;
-  }
-  sayName() {
-    console.log('Hi, I am a ', this.name + '.');
-  }
-  get area() {
-    return this.height * this.width;
-  }
-  set area(value) {
-    this._area = value;
-  }
-}
-
-class Square extends Rectangle {
-  constructor(length) {
-    this.height; // ReferenceError, super needs to be called first!
-
-    // Here, it calls the parent class's constructor with lengths
-    // provided for the Rectangle's width and height
-    super(length, length);
-
-    // Note: In derived classes, super() must be called before you
-    // can use 'this'. Leaving this out will cause a reference error.
-    this.name = 'Square';
-  }
-}
- -

Super-calling static methods

- -

You are also able to call super on static methods.

- -
class Rectangle {
-  static logNbSides() {
-    return 'I have 4 sides';
-  }
-}
-
-class Square extends Rectangle {
-  static logDescription() {
-    return super.logNbSides() + ' which are all equal';
-  }
-}
-Square.logDescription(); // 'I have 4 sides which are all equal'
-
- -

Deleting super properties will throw an error

- -

You cannot use the delete operator and super.prop or super[expr] to delete a parent class' property, it will throw a {{jsxref("ReferenceError")}}.

- -
class Base {
-  foo() {}
-}
-class Derived extends Base {
-  delete() {
-    delete super.foo; // this is bad
-  }
-}
-
-new Derived().delete(); // ReferenceError: invalid delete involving 'super'. 
- -

super.prop cannot overwrite non-writable properties

- -

When defining non-writable properties with e.g. {{jsxref("Object.defineProperty")}}, super cannot overwrite the value of the property.

- -
class X {
-  constructor() {
-    Object.defineProperty(this, 'prop', {
-      configurable: true,
-      writable: false,
-      value: 1
-    });
-  }
-}
-
-class Y extends X {
-  constructor() {
-    super();
-  }
-  foo() {
-    super.prop = 2;   // Cannot overwrite the value.
-  }
-}
-
-var y = new Y();
-y.foo(); // TypeError: "prop" is read-only
-console.log(y.prop); // 1
-
- -

Using super.prop in object literals

- -

Super can also be used in the object initializer / literal notation. In this example, two objects define a method. In the second object, super calls the first object's method. This works with the help of {{jsxref("Object.setPrototypeOf()")}} with which we are able to set the prototype of obj2 to obj1, so that super is able to find method1 on obj1.

- -
var obj1 = {
-  method1() {
-    console.log('method 1');
-  }
-}
-
-var obj2 = {
-  method2() {
-    super.method1();
-  }
-}
-
-Object.setPrototypeOf(obj2, obj1);
-obj2.method2(); // logs "method 1"
-
- -

Özellikler

- - - - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-super-keyword', 'super')}}
- -

Tarayıcı uyumluluğu

- - - -

{{Compat("javascript.operators.super")}}

- -

Ayrıca bakınız

- - diff --git "a/files/tr/web/javascript/reference/operat\303\266rler/this/index.html" "b/files/tr/web/javascript/reference/operat\303\266rler/this/index.html" deleted file mode 100644 index 674e577187..0000000000 --- "a/files/tr/web/javascript/reference/operat\303\266rler/this/index.html" +++ /dev/null @@ -1,347 +0,0 @@ ---- -title: this -slug: Web/JavaScript/Reference/Operatörler/this -translation_of: Web/JavaScript/Reference/Operators/this ---- -
{{jsSidebar("Operators")}}
- -

Fonksiyon'un this anahtar kelimesi diğer dillere göre birazcık farklı davranır. Ayrıca strict modu ve non-strict modu arasında farklılıklar bulunur.

- -

Çoğunlukla, this'in değeri fonksiyonun çağrılma biçimine göre belirlenir. Çalışma esnasında değeri değiştirilemez, ve her fonksiyonu çağırışta farklı olabilir. ES5 bu adreste bind method to set the value of a function's this regardless of how it's called.

- -

Sözdizimi

- -
this
- -

Global içerik

- -

Global konumda (fonksiyon dışında), this global nesnesini referans gösterir, strict modunda olmak bu durumu değiştirmez..

- -
console.log(this.document === document); // true
-
-// Web browserlerinde window objesi global objedir.:
-console.log(this === window); // true
-
-this.a = 37;
-console.log(window.a); // 37
-
- -

Function içerik

- -

Fonksiyon içerisinde, this'in değeri fonksiyonun nasıl çağrıldığına bağlıdır..

- -

Basit çağrı

- -
function f1(){
-  return this;
-}
-
-f1() === window; // global obje
-
- -

Bu durumda, this'in değeri çağrı ile ayarlanmaz. Kod strict modda olmadığı sürece, this'in değeri mutlaka obje olmalıdır bu yüzdende default değer olan global objesi döner.

- -
function f2(){
-  "use strict"; // strict modu içerisinde çalıştıralım
-  return this;
-}
-
-f2() === undefined;
-
- -

Strict modu içerisinde, this'in değeri çalıştırılma içeriğine nasıl girdiyse o şekilde kalır. Eğer tanımlanmamışsa, undefined olarak kalır. Ayrıca tüm değerlere eşitlenebilir, örneğin null yada 42 yada "I am not this".

- -
Not: İkinci örnekte, this undefined olmalıdır, çünkü f2 taban belirtilmeden çağrılmıştır. (örn: window.f2()). Bu özellik bazı browserlerde desteklenmemektedir. strict mod henüz geliştirme aşamasındayken çoğu browser yanlış davranarak window objesini döndürür.
- -

Obje methodu cağrısı

- -

Fonksiyon bir objenin methodu olarak çağrıldığında, this çağrıldığı obje olarak atanacaktır.

- -

In the following example, when o.f() is invoked, inside the function this is bound to the o object.

- -
var o = {
-  prop: 37,
-  f: function() {
-    return this.prop;
-  }
-};
-
-console.log(o.f()); // logs 37
-
- -

Note that this behavior is not at all affected by how or where the function was defined. In the previous example, we defined the function inline as the f member during the definition of o. However, we could have just as easily defined the function first and later attached it to o.f. Doing so results in the same behavior:

- -
var o = {prop: 37};
-
-function independent() {
-  return this.prop;
-}
-
-o.f = independent;
-
-console.log(o.f()); // logs 37
-
- -

This demonstrates that it matters only that the function was invoked from the f member of o.

- -

Similarly, the this binding is only affected by the most immediate member reference. In the following example, when we invoke the function, we call it as a method g of the object o.b. This time during execution, this inside the function will refer to o.b. The fact that the object is itself a member of o has no consequence; the most immediate reference is all that matters.

- -
o.b = {g: independent, prop: 42};
-console.log(o.b.g()); // logs 42
-
- -

this on the object's prototype chain

- -

The same notion holds true for methods defined somewhere on the object's prototype chain. If the method is on an object's prototype chain, this refers to the object the method was called on, as if the method was on the object.

- -
var o = {f:function(){ return this.a + this.b; }};
-var p = Object.create(o);
-p.a = 1;
-p.b = 4;
-
-console.log(p.f()); // 5
-
- -

In this example, the object assigned to the variable p doesn't have its own f property, it inherits it from its prototype. But it doesn't matter that the lookup for f eventually finds a member with that name on o; the lookup began as a reference to p.f, so this inside the function takes the value of the object referred to as p. That is, since f is called as a method of p, its this refers to p. This is an interesting feature of JavaScript's prototype inheritance.

- -

this with a getter or setter

- -

Again, the same notion holds true when a function is invoked from a getter or a setter. A function used as getter or setter has its this bound to the object from which the property is being set or gotten.

- -
function modulus(){
-  return Math.sqrt(this.re * this.re + this.im * this.im);
-}
-
-var o = {
-  re: 1,
-  im: -1,
-  get phase(){
-    return Math.atan2(this.im, this.re);
-  }
-};
-
-Object.defineProperty(o, 'modulus', {
-    get: modulus, enumerable:true, configurable:true});
-
-console.log(o.phase, o.modulus); // logs -0.78 1.4142
-
- -

As a constructor

- -

When a function is used as a constructor (with the new keyword), its this is bound to the new object being constructed.

- -

Note: while the default for a constructor is to return the object referenced by this, it can instead return some other object (if the return value isn't an object, then the this object is returned).

- -
/*
- * Constructors work like this:
- *
- * function MyConstructor(){
- *   // Actual function body code goes here.
- *   // Create properties on |this| as
- *   // desired by assigning to them.  E.g.,
- *   this.fum = "nom";
- *   // et cetera...
- *
- *   // If the function has a return statement that
- *   // returns an object, that object will be the
- *   // result of the |new| expression.  Otherwise,
- *   // the result of the expression is the object
- *   // currently bound to |this|
- *   // (i.e., the common case most usually seen).
- * }
- */
-
-function C(){
-  this.a = 37;
-}
-
-var o = new C();
-console.log(o.a); // logs 37
-
-
-function C2(){
-  this.a = 37;
-  return {a:38};
-}
-
-o = new C2();
-console.log(o.a); // logs 38
-
- -

In the last example (C2), because an object was returned during construction, the new object that this was bound to simply gets discarded. (This essentially makes the statement "this.a = 37;" dead code. It's not exactly dead, because it gets executed, but it can be eliminated with no outside effects.)

- -

call and apply

- -

Where a function uses the this keyword in its body, its value can be bound to a particular object in the call using the call or apply methods that all functions inherit from Function.prototype.

- -
function add(c, d){
-  return this.a + this.b + c + d;
-}
-
-var o = {a:1, b:3};
-
-// The first parameter is the object to use as
-// 'this', subsequent parameters are passed as
-// arguments in the function call
-add.call(o, 5, 7); // 1 + 3 + 5 + 7 = 16
-
-// The first parameter is the object to use as
-// 'this', the second is an array whose
-// members are used as the arguments in the function call
-add.apply(o, [10, 20]); // 1 + 3 + 10 + 20 = 34
-
- -

Note that with call and apply, if the value passed as this is not an object, an attempt will be made to convert it to an object using the internal ToObject operation. So if the value passed is a primitive like 7 or 'foo', it will be converted to an Object using the related constructor, so the primitive number 7 is converted to an object as if by new Number(7) and the string 'foo' to an object as if by new String('foo'), e.g.

- -
function bar() {
-  console.log(Object.prototype.toString.call(this));
-}
-
-bar.call(7); // [object Number]
-
- -

The bind method

- -

ECMAScript 5 introduced Function.prototype.bind. Calling f.bind(someObject) creates a new function with the same body and scope as f, but where this occurs in the original function, in the new function it is permanently bound to the first argument of bind, regardless of how the function is being used.

- -
function f(){
-  return this.a;
-}
-
-var g = f.bind({a:"azerty"});
-console.log(g()); // azerty
-
-var o = {a:37, f:f, g:g};
-console.log(o.f(), o.g()); // 37, azerty
-
- -

As a DOM event handler

- -

When a function is used as an event handler, its this is set to the element the event fired from (some browsers do not follow this convention for listeners added dynamically with methods other than addEventListener).

- -
// When called as a listener, turns the related element blue
-function bluify(e){
-  // Always true
-  console.log(this === e.currentTarget);
-  // true when currentTarget and target are the same object
-  console.log(this === e.target);
-  this.style.backgroundColor = '#A5D9F3';
-}
-
-// Get a list of every element in the document
-var elements = document.getElementsByTagName('*');
-
-// Add bluify as a click listener so when the
-// element is clicked on, it turns blue
-for(var i=0 ; i<elements.length ; i++){
-  elements[i].addEventListener('click', bluify, false);
-}
- -

In an in–line event handler

- -

When code is called from an in–line handler, its this is set to the DOM element on which the listener is placed:

- -
<button onclick="alert(this.tagName.toLowerCase());">
-  Show this
-</button>
-
- -

The above alert shows button. Note however that only the outer code has its this set this way:

- -
<button onclick="alert((function(){return this}()));">
-  Show inner this
-</button>
-
- -

In this case, the inner function's this isn't set so it returns the global/window object (i.e. the default object in non–strict mode where this isn't set by the call).

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-this-keyword', 'The this keyword')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.1.1', 'The this keyword')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-11.1.1', 'The this keyword')}}{{Spec2('ES3')}} 
{{SpecName('ES1', '#sec-11.1.1', 'The this keyword')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

See also

- - diff --git "a/files/tr/web/javascript/reference/operat\303\266rler/typeof/index.html" "b/files/tr/web/javascript/reference/operat\303\266rler/typeof/index.html" deleted file mode 100644 index deccfd8925..0000000000 --- "a/files/tr/web/javascript/reference/operat\303\266rler/typeof/index.html" +++ /dev/null @@ -1,259 +0,0 @@ ---- -title: typeof -slug: Web/JavaScript/Reference/Operatörler/typeof -translation_of: Web/JavaScript/Reference/Operators/typeof ---- -
{{jsSidebar("Operatörler")}}
- -

Typeof operatörü, değerlendirilmemiş işlenenin türünü gösteren bir dize döndürür.

- -
{{EmbedInteractiveExample("pages/js/expressions-typeof.html")}}
- - - -

Sözdizimi

- -

The typeof operator is followed by its operand:

- -
typeof operand
-or
-typeof (operand)
-
- - - -

Parametreler

- -

operand is an expression representing the object or {{Glossary("Primitive", "primitive")}} whose type is to be returned.

- -

Parantez isteğe bağlıdır.

- -

Description

- -

The following table summarizes the possible return values of typeof. For more information about types and primitives, see also the JavaScript data structure page.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TypeResult
Undefined"undefined"
Null"object" (see below)
Boolean"boolean"
Number"number"
String"string"
Symbol (new in ECMAScript 2015)"symbol"
Host object (provided by the JS environment)Implementation-dependent
Function object (implements [[Call]] in ECMA-262 terms)"function"
Any other object"object"
- -

Örnekler

- -
// Sayılar
-typeof 37 === 'number';
-typeof 3.14 === 'number';
-typeof(42) === 'number';
-typeof Math.LN2 === 'number';
-typeof Infinity === 'number';
-typeof NaN === 'number'; // Despite being "Not-A-Number"
-typeof Number(1) === 'number'; // but never use this form!
-
-
-// Metinler
-typeof '' === 'string';
-typeof 'bla' === 'string';
-typeof '1' === 'string'; // note that a number within a string is still typeof string
-typeof (typeof 1) === 'string'; // typeof always returns a string
-typeof String('abc') === 'string'; // but never use this form!
-
-
-// Booleans
-typeof true === 'boolean';
-typeof false === 'boolean';
-typeof Boolean(true) === 'boolean'; // but never use this form!
-
-
-// Symbols
-typeof Symbol() === 'symbol'
-typeof Symbol('foo') === 'symbol'
-typeof Symbol.iterator === 'symbol'
-
-
-// Undefined
-typeof undefined === 'undefined';
-typeof declaredButUndefinedVariable === 'undefined';
-typeof undeclaredVariable === 'undefined';
-
-
-// Objeler
-typeof {a: 1} === 'object';
-
-// use Array.isArray or Object.prototype.toString.call
-// to differentiate regular objects from arrays
-typeof [1, 2, 4] === 'object';
-
-typeof new Date() === 'object';
-
-
-// The following is confusing. Don't use!
-typeof new Boolean(true) === 'object';
-typeof new Number(1) === 'object';
-typeof new String('abc') === 'object';
-
-
-// Fonksiyonlar
-typeof function() {} === 'function';
-typeof class C {} === 'function';
-typeof Math.sin === 'function';
-
- -

null

- -
// This stands since the beginning of JavaScript
-typeof null === 'object';
-
- -

In the first implementation of JavaScript, JavaScript values were represented as a type tag and a value. The type tag for objects was 0. null was represented as the NULL pointer (0x00 in most platforms). Consequently, null had 0 as type tag, hence the bogus typeof return value. (reference)

- -

A fix was proposed for ECMAScript (via an opt-in), but was rejected. It would have resulted in typeof null === 'null'.

- -

new operatör kullanımı

- -
// All constructor functions while instantiated with 'new' keyword will always be typeof 'object'
-var str = new String('String');
-var num = new Number(100);
-
-typeof str; // It will return 'object'
-typeof num; // It will return 'object'
-
-// But there is a exception in case of Function constructor of Javascript
-
-var func = new Function();
-
-typeof func; // It will return 'function'
-
- -

Parantezlere ihtiyaç var

- -
// Parentheses will be very much useful to determine the data type for expressions.
-var iData = 99;
-
-typeof iData + ' Wisen'; // It will return 'number Wisen'
-typeof (iData + ' Wisen'); // It will return 'string'
-
-
-
- -

Düzenli İfadeler

- -

Callable regular expressions were a non-standard addition in some browsers.

- -
typeof /s/ === 'function'; // Chrome 1-12 Non-conform to ECMAScript 5.1
-typeof /s/ === 'object';   // Firefox 5+  Conform to ECMAScript 5.1
-
- -

Temporal Dead Zone errors

- -

Before ECMAScript 2015, typeof was always guaranteed to return a string for any operand it was supplied with. But with the addition of non-hoisted, block-scoped let and const, using typeof on let and const variables in a block before they are declared will throw a ReferenceError. This is in contrast with undeclared variables, for which typeof will return 'undefined'. Block scoped variables are in a "temporal dead zone" from the start of the block until the initialization is processed, during which, it will throw an error if accessed.

- -
typeof undeclaredVariable === 'undefined';
-typeof newLetVariable; let newLetVariable; // ReferenceError
-typeof newConstVariable; const newConstVariable = 'hello'; // ReferenceError
-
- -

İstisnalar

- -

All current browsers expose a non-standard host object {{domxref("document.all")}} with type Undefined.

- -
typeof document.all === 'undefined';
-
- -

Although the specification allows custom type tags for non-standard exotic objects, it requires those type tags to be different from the predefined ones. The case of document.all having type tag 'undefined' must be classified as an exceptional violation of the rules.

- -

Özellikler

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-typeof-operator', 'The typeof Operator')}}{{Spec2('ESDraft')}}
{{SpecName('ES6', '#sec-typeof-operator', 'The typeof Operator')}}{{Spec2('ES6')}}
{{SpecName('ES5.1', '#sec-11.4.3', 'The typeof Operator')}}{{Spec2('ES5.1')}}
{{SpecName('ES3', '#sec-11.4.3', 'The typeof Operator')}}{{Spec2('ES3')}}
{{SpecName('ES1', '#sec-11.4.3', 'The typeof Operator')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
- -

Browser compatibility

- - - -

{{Compat("javascript.operators.typeof")}}

- -

IE özel notlar

- -

On IE 6, 7, and 8 a lot of host objects are objects and not functions. For example:

- -
typeof alert === 'object'
- -

Bakabilirsiniz

- - diff --git "a/files/tr/web/javascript/veri_yap\304\261s\304\261/index.html" "b/files/tr/web/javascript/veri_yap\304\261s\304\261/index.html" deleted file mode 100644 index 693d18233a..0000000000 --- "a/files/tr/web/javascript/veri_yap\304\261s\304\261/index.html" +++ /dev/null @@ -1,298 +0,0 @@ ---- -title: JavaScript veri tipi ve veri yapısı -slug: Web/JavaScript/Veri_Yapısı -tags: - - Başlangıç - - JavaScript - - Veri Türleri -translation_of: Web/JavaScript/Data_structures ---- -
{{jsSidebar("More")}}
- -

Programlama dilleri dil ile birlikte gelen sabit veri yapılarına sahiptir, fakat bu veri yapıları dilden dile değişiklik gösterir. Bu makale JavaScript'teki sabit veri yapılarını ve bu veri yapılarının özelliklerini listeler; böylece bu veri yapıları kullanılarak farklı veri yapıları yaratılabilir. Makale boyunca karşılaştırmanın mümkün olduğu bölümlerde, farklı dillerle kıyaslama yapılmıştır.

- -

Dinamik Veri Tipi

- -

JavaScript esnek (ya da dinamik) veri tipine sahip bir dildir. JavaScript dilinde değişkenler belirli bir veri tipi ile direkt ve sabit olarak ilişkilendirilmez ve herhangi bir değişkene herhangi bir veri tipine sahip bir değer atanabilir, bu değer daha sonra farklı bir veri tipinin değeri ile değiştirilebilir.

- -
var foo = 42;    // foo değişkeni şuan bir sayıdır
-foo     = 'bar'; // foo değişkeni şuan karakter dizisidir
-foo     = true;  // foo değişkeni şuan boolean veri türüdür
-
- -

Veri Tipleri

- -

Son ECMAScript standartları 7 veri tipi tanımlar:

- - - -

İlkel (Primitive)  değerler

- -

Nesne dışındaki bütün veri tipleri sonradan değiştirilemez değerler tanımlar. Örnek olarak C dilinin tersine karakter dizileri (String) değiştirilemez. Bu tipteki değerler ilkel değerler (primitive values) olarak tanımlanır.

- -

Boolean tipi

- -

Boolean veri tipi doğru ( true ) ve yanlış ( false ) olmak üzere iki mantıksal değerden birine sahip olan veri tiplerini temsil eder.

- -

Null tipi

- -

Boş olan değişkenlerin alabiileceği tek değer vardır: null. Daha fazla detay için buraya bakınız {{jsxref("null")}} and {{Glossary("Null")}}.

- -

Undefined tipi

- -

Herhangi bir değer atanmamış değişkenlerin değeri undefined (tanımlanmamış)dır. Daha fazla detay için buraya {{jsxref("undefined")}}  ve buraya {{Glossary("Undefined")}} bakınız.

- -

Number type

- -

According to the ECMAScript standard, there is only one number type: the double-precision 64-bit binary format IEEE 754 value (numbers between -(253 -1) and 253 -1). There is no specific type for integers. In addition to being able to represent floating-point numbers, the number type has three symbolic values: +Infinity, -Infinity, and NaN (not-a-number).

- -

To check for the largest available value or smallest available value within +/-Infinity, you can use the constants {{jsxref("Number.MAX_VALUE")}} or {{jsxref("Number.MIN_VALUE")}} and starting with ECMAScript 2015, you are also able to check if a number is in the double-precision floating-point number range using {{jsxref("Number.isSafeInteger()")}} as well as {{jsxref("Number.MAX_SAFE_INTEGER")}} and {{jsxref("Number.MIN_SAFE_INTEGER")}}. Beyond this range, integers in JavaScript are not safe anymore and will be a double-precision floating point approximation of the value.

- -

The number type has only one integer that has two representations: 0 is represented as -0 and +0. ("0" is an alias for +0). In the praxis, this has almost no impact. For example +0 === -0 is true. However, you are able to notice this when you divide by zero:

- -
> 42 / +0
-Infinity
-> 42 / -0
--Infinity
-
- -

Although a number often represents only its value, JavaScript provides some binary operators. These can be used to represent several Boolean values within a single number using bit masking. However, this is usually considered a bad practice, since JavaScript offers other means to represent a set of Booleans (like an array of Booleans or an object with Boolean values assigned to named properties). Bit masking also tends to make the code more difficult to read, understand, and maintain. It may be necessary to use such techniques in very constrained environments, like when trying to cope with the storage limitation of local storage or in extreme cases when each bit over the network counts. This technique should only be considered when it is the last measure that can be taken to optimize size.

- -

String type

- -

JavaScript's {{jsxref("Global_Objects/String", "String")}} type is used to represent textual data. It is a set of "elements" of 16-bit unsigned integer values. Each element in the String occupies a position in the String. The first element is at index 0, the next at index 1, and so on. The length of a String is the number of elements in it.

- -

Unlike in languages like C, JavaScript strings are immutable. This means that once a string is created, it is not possible to modify it. However, it is still possible to create another string based on an operation on the original string. For example:

- - - -

Beware of "stringly-typing" your code!

- -

It can be tempting to use strings to represent complex data. Doing this comes with short-term benefits:

- - - -

With conventions, it is possible to represent any data structure in a string. This does not make it a good idea. For instance, with a separator, one could emulate a list (while a JavaScript array would be more suitable). Unfortunately, when the separator is used in one of the "list" elements, then, the list is broken. An escape character can be chosen, etc. All of this requires conventions and creates an unnecessary maintenance burden.

- -

Use strings for textual data. When representing complex data, parse strings and use the appropriate abstraction.

- -

Symbol type

- -

Symbols are new to JavaScript in ECMAScript 2015. A Symbol is a unique and immutable primitive value and may be used as the key of an Object property (see below). In some programming languages, Symbols are called atoms. For more details see {{Glossary("Symbol")}} and the {{jsxref("Symbol")}} object wrapper in JavaScript.

- -

Objects

- -

In computer science, an object is a value in memory which is possibly referenced by an {{Glossary("Identifier", "identifier")}}.

- -

Properties

- -

In JavaScript, objects can be seen as a collection of properties. With the object literal syntax, a limited set of properties are initialized; then properties can be added and removed. Property values can be values of any type, including other objects, which enables building complex data structures. Properties are identified using key values. A key value is either a String or a Symbol value.

- -

There are two types of object properties which have certain attributes: The data property and the accessor property.

- -

Data property

- -

Associates a key with a value and has the following attributes:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Attributes of a data property
AttributeTypeDescriptionDefault value
[[Value]]Any JavaScript typeThe value retrieved by a get access of the property.undefined
[[Writable]]BooleanIf false, the property's [[Value]] can't be changed.false
[[Enumerable]]BooleanIf true, the property will be enumerated in for...in loops. See also Enumerability and ownership of propertiesfalse
[[Configurable]]BooleanIf false, the property can't be deleted, can't be changed to an accessor property and attributes other than [[Value]] and [[Writable]] can't be changed.false
- - - - - - - - - - - - - - - - - - - - - - - - - -
Obsolete attributes (as of ECMAScript 3, renamed in ECMAScript 5)
AttributeTypeDescription
Read-onlyBooleanReversed state of the ES5 [[Writable]] attribute.
DontEnumBooleanReversed state of the ES5 [[Enumerable]] attribute.
DontDeleteBooleanReversed state of the ES5 [[Configurable]] attribute.
- -

Accessor property

- -

Associates a key with one or two accessor functions (get and set) to retrieve or store a value and has the following attributes:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Attributes of an accessor property
AttributeTypeDescriptionDefault value
[[Get]]Function object or undefinedThe function is called with an empty argument list and retrieves the property value whenever a get access to the value is performed. See also get.undefined
[[Set]]Function object or undefinedThe function is called with an argument that contains the assigned value and is executed whenever a specified property is attempted to be changed. See also set.undefined
[[Enumerable]]BooleanIf true, the property will be enumerated in for...in loops.false
[[Configurable]]BooleanIf false, the property can't be deleted and can't be changed to a data property.false
- -
-

Note: Attribute is usually used by JavaScript engine, so you can't directly access it (see more about Object.defineProperty()). That's why the attribute is put in double square brackets instead of single.

-
- -

"Normal" objects, and functions

- -

A JavaScript object is a mapping between keys and values. Keys are strings (or {{jsxref("Symbol")}}s) and values can be anything. This makes objects a natural fit for hashmaps.

- -

Functions are regular objects with the additional capability of being callable.

- -

Dates

- -

When representing dates, the best choice is to use the built-in Date utility in JavaScript.

- -

Indexed collections: Arrays and typed Arrays

- -

Arrays are regular objects for which there is a particular relationship between integer-key-ed properties and the 'length' property. Additionally, arrays inherit from Array.prototype which provides to them a handful of convenient methods to manipulate arrays. For example, indexOf (searching a value in the array) or push (adding an element to the array), etc. This makes Arrays a perfect candidate to represent lists or sets.

- -

Typed Arrays are new to JavaScript with ECMAScript 2015 and present an array-like view of an underlying binary data buffer. The following table helps you to find the equivalent C data types:

- -

{{page("/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray", "TypedArray_objects", "", 0, 3)}}

- -

Keyed collections: Maps, Sets, WeakMaps, WeakSets

- -

These data structures take object references as keys and are introduced in ECMAScript Edition 6. {{jsxref("Set")}} and {{jsxref("WeakSet")}} represent a set of objects, while {{jsxref("Map")}} and {{jsxref("WeakMap")}} associate a value to an object. The difference between Maps and WeakMaps is that in the former, object keys can be enumerated over. This allows garbage collection optimizations in the latter case.

- -

One could implement Maps and Sets in pure ECMAScript 5. However, since objects cannot be compared (in the sense of "less than" for instance), look-up performance would necessarily be linear. Native implementations of them (including WeakMaps) can have look-up performance that is approximately logarithmic to constant time.

- -

Usually, to bind data to a DOM node, one could set properties directly on the object or use data-* attributes. This has the downside that the data is available to any script running in the same context. Maps and WeakMaps make it easy to privately bind data to an object.

- -

Structured data: JSON

- -

JSON (JavaScript Object Notation) is a lightweight data-interchange format, derived from JavaScript but used by many programming languages. JSON builds universal data structures. See {{Glossary("JSON")}} and {{jsxref("JSON")}} for more details.

- -

More objects in the standard library

- -

JavaScript has a standard library of built-in objects. Please have a look at the reference to find out about more objects.

- -

Determining types using the typeof operator

- -

The typeof operator can help you to find the type of your variable. Please read the reference page for more details and edge cases.

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-8', 'Types')}}{{Spec2('ES5.1')}}
{{SpecName('ES2015', '#sec-ecmascript-data-types-and-values', 'ECMAScript Data Types and Values')}}{{Spec2('ES2015')}}Added Symbol.
{{SpecName('ESDraft', '#sec-ecmascript-data-types-and-values', 'ECMAScript Data Types and Values')}}{{Spec2('ESDraft')}}
- -

See also

- - -- cgit v1.2.3-54-g00ecf