aboutsummaryrefslogtreecommitdiff
path: root/files/de/web/javascript/guide/working_with_objects/index.html
blob: 8bd40a23e7042a66b0e25646fb68f3a82a38e6ad (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
---
title: Mit Objekten arbeiten
slug: Web/JavaScript/Guide/Working_with_Objects
tags:
  - Beginner
  - Comparing object
  - Constructor
  - Document
  - Guide
  - JavaScript
  - Object
  - l10n:priority
translation_of: Web/JavaScript/Guide/Working_with_Objects
original_slug: Web/JavaScript/Guide/Mit_Objekten_arbeiten
---
<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Regular_Expressions", "Web/JavaScript/Guide/Feinheiten_des_Objektmodells")}}</div>

<p class="summary">JavaScript ist nach einem einfachen objekt-basierten Muster entworfen. Ein Objekt ist eine Sammlung von Eigenschaften und eine Eigenschaft ist eine Verbindung von einem Namen und einem Wert. Der Wert einer Eigenschaft kann eine Funktion sein. In diesem Fall wird die Eigenschaft Methode genannt. Zusätzlich zu Objekten, die vom Browser vordefiniert sind, können auch eigene Objekte definiert werden. Dieses Kapitel beschreibt, wie Objekte, Eigenschaften, Funktionen und Methoden benutzt und eigene Objekte erzeugt werden können.</p>

<h2 id="Objekte_Übersicht">Objekte Übersicht</h2>

<p>Objekte in JavaScript, wie in vielen anderen Programmiersprachen, können mit Objekten aus dem realen Leben verglichen werden. Das Konzept der Objekte in JavaScript kann mit greifbaren Objekten aus der realen Welt verstanden werden.</p>

<p>In JavaScript ist ein Objekt eine für sich stehende Einheit mit Eigenschaften und Typ. Vergleichbar mit einer Tasse zum Beispiel. Eine Tasse ist ein Objekt mit Eigenschaften. Eine Tasse hat eine Farbe, ein Design, ein Gewicht, ein Material, aus dem sie erstellt wurde, usw. Ebenso können JavaScript Objekte Eigenschaften besitzen, die Ihre Besonderheiten definieren.</p>

<h2 id="Objekte_und_Eigenschaften">Objekte und Eigenschaften</h2>

<p>Ein JavaScript Objekt besitzt mit ihm verbundene Eigenschaften. Eine Eigenschaft eines Objekts kann als Variable erklärt werden, die dem Objekt angeheftet ist. Objekteigenschaften sind grundsätzlich das Gleiche wie übliche Variablen ausser der Verknüpfung mit Objekten. Die Eigenschaften eines Objekts definieren seine Charakteristik. Auf die Eigenschaften eines Objekt kann mit einer einfachen Punkt-Notation zugegriffen werden:</p>

<pre class="brush: js">objectName.propertyName
</pre>

<p>Wie bei allen JavaScript-Variablen sind Objektname (eine normale Variable) und Attribute groß-, und kleinschreibungsabhängig. Ein Attribut wird definiert, indem es einen Wert zugewiesen bekommt. Zum Beispiel: Ein Objekt namens <code>myCar</code> mit den Attributen <code>make</code>, <code>model</code>, und <code>year</code>:</p>

<pre class="brush: js">var myCar = new Object();
myCar.make = "Ford";
myCar.model = "Mustang";
myCar.year = 1969;
</pre>

<p>Nicht initialisierte Eigenschaften eines Objektes haben den Wert {{jsxref("undefined")}} (nicht {{jsxref("null")}}).</p>

<pre class="brush: js">myCar.color; // undefined</pre>

<p>Eigenschaften von JavaScript-Objekten können auch mit der Klammernotation (für weitere Informationen siehe <a href="/de/docs/Web/JavaScript/Reference/Operators/Property_Accessors">property accessors</a>). Objekte werden manchmal assoziative Arrays genannt da jede Eigenschaft mit einer Zeichenkette assoziiert ist mit der man auf die Eigenschaft zugreifen kann. Zum Beispiel kann man auf die Eigenschaften des Objekts <code>myCar</code> folgendermassen zugreifen:</p>

<pre class="brush: js">myCar["make"] = "Ford";
myCar["model"] = "Mustang";
myCar["year"] = 1969;
</pre>

<p>Der Name einer Objekteigenschaft kann ein valider JavaScript String sein. Dies kann auch alles sein, was in einen String convertiert werden kann, inklusive eines leeren Strings. Immer, wenn der Name einer Eigenschaft kein valider JavaScript Bezeichner ist (zum Beispiel ein Name mit einem Leerzeichen oder einem minus oder ein Name der mit einer Ziffer beginnt), kann dieses nur über die Klammernotation erreicht werden. Diese Notation ist zusätzlich sehr hilfreich, wenn Namen von Eigenschaften dynamisch ermittelt werden (Wenn die Namen nicht bis zur Laufzeit ermittelt werden können). Im folgenden ein Beispiel:</p>

<pre class="brush: js">// 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);
</pre>

<p>Zu bemerken ist, dass alle Schlüssel in der Klammernotation zum Typ Strings konvertiert werden, weil in JavaScript nur Strings als Schlüssel bei Objekte erlaubt sind. Zum Beispiel wird im orberen Beispiel <code>obj</code> konvertiert wenn es in <code>myObj</code> benutzt wird. JavaScript ruft die <code>obj.toString()</code> Methode auf und benutzt den resultierenden String als neuen Schlüssel.</p>

<p>Man kann eine Eigenschaft auch erreichen, indem eine Variable vom Typ String benutzt wird:</p>

<pre class="brush: js">var propertyName = 'make';
myCar[propertyName] = 'Ford';

propertyName = 'model';
myCar[propertyName] = 'Mustang';
</pre>

<p>Man kann die Klammernotation mit <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in">for...in</a></code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in"> </a>nutzen, um über alle enumerable (aufzählbaren) Eigenschaften eines Objektes zu iterieren. Um dieses zu zeigen wie das funktioniert, zeigt die folgende Funktion die Eigenschaften eines Objektes, wenn eine Objekt und der Name des Objektes der Funktion als Parameter übergeben werden:</p>

<pre class="brush: js">function showProps(obj, objName) {
  var result = '';
  for (var i in obj) {
    // obj.hasOwnProperty() wird benutzt um Eigenschaften aus der Prototypen-Kette herauszufiltern
    if (obj.hasOwnProperty(i)) {
      result += objName + '.' + i + ' = ' + obj[i] + '\n';
    }
  }
  return result;
}
</pre>

<p>So gibt der Aufruf <code>showProps(myCar, "myCar")</code> folgenden Rückgabewert zurück:</p>

<pre class="brush: js">myCar.make = Ford
myCar.model = Mustang
myCar.year = 1969</pre>

<h2 id="Enumerate_the_properties_of_an_object">Enumerate the properties of an object</h2>

<p>Starting with <a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/ECMAScript_5_support_in_Mozilla" title="en-US/docs/JavaScript/ECMAScript 5 support in Mozilla">ECMAScript 5</a>, there are three native ways to list/traverse object properties:</p>

<ul>
 <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...in" title="en-US/docs/JavaScript/Reference/Statements/for...in">for...in</a></code> loops<br>
  This method traverses all enumerable properties of an object and its prototype chain</li>
 <li>{{jsxref("Object.keys", "Object.keys(o)")}}<br>
  This method returns an array with all the own (not in the prototype chain) enumerable properties' names ("keys") of an object <code>o</code>.</li>
 <li>{{jsxref("Object.getOwnPropertyNames", "Object.getOwnPropertyNames(o)")}}<br>
  This method returns an array containing all own properties' names (enumerable or not) of an object <code>o</code>.</li>
</ul>

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

<pre class="brush: js">function listAllProperties(o) {
	var objectToInspect;
	var result = [];

	for(objectToInspect = o; objectToInspect !== null; objectToInspect = Object.getPrototypeOf(objectToInspect)) {
      result = result.concat(Object.getOwnPropertyNames(objectToInspect));
	}

	return result;
}
</pre>

<p>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.</p>

<h2 id="Creating_new_objects">Creating new objects</h2>

<p>JavaScript has a number of predefined objects. In addition, you can create your own objects. You can create an object using an <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer">object initializer</a>. Alternatively, you can first create a constructor function and then instantiate an object invoking that function in conjunction with the <code>new</code> operator.</p>

<h3 id="Using_object_initializers"><a id="Object_initializers" name="Object_initializers">Using object initializers</a></h3>

<p>In addition to creating objects using a constructor function, you can create objects using an <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer">object initializer</a>. Using object initializers is sometimes referred to as creating objects with literal notation. "Object initializer" is consistent with the terminology used by C++.</p>

<p>The syntax for an object using an object initializer is:</p>

<pre class="brush: js">var obj = { property_1:   value_1,   // property_# may be an identifier...
            2:            value_2,   // or a number...
            // ...,
            'property n': value_n }; // or a string
</pre>

<p>where <code>obj</code> is the name of the new object, each <code>property_<em>i</em></code> is an identifier (either a name, a number, or a string literal), and each <code>value_<em>i</em></code> is an expression whose value is assigned to the <code>property_<em>i</em></code>. The <code>obj</code> 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.)</p>

<p>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 <code>new Object()</code> were made; that is, objects made from object literal expressions are instances of <code>Object</code>.</p>

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

<pre class="brush: js">if (cond) var x = {greeting: 'hi there'};
</pre>

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

<pre class="brush: js">var myHonda = {color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}};
</pre>

<p>You can also use object initializers to create arrays. See <a href="/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Array_literals">array literals</a>.</p>

<h3 id="Using_a_constructor_function">Using a constructor function</h3>

<p>Alternatively, you can create an object with these two steps:</p>

<ol>
 <li>Define the object type by writing a constructor function. There is a strong convention, with good reason, to use a capital initial letter.</li>
 <li>Create an instance of the object with <code>new</code>.</li>
</ol>

<p>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 <code>Car</code>, and you want it to have properties for make, model, and year. To do this, you would write the following function:</p>

<pre class="brush: js">function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}
</pre>

<p>Notice the use of <code>this</code> to assign values to the object's properties based on the values passed to the function.</p>

<p>Now you can create an object called <code>mycar</code> as follows:</p>

<pre class="brush: js">var mycar = new Car('Eagle', 'Talon TSi', 1993);
</pre>

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

<p>You can create any number of <code>Car</code> objects by calls to <code>new</code>. For example,</p>

<pre class="brush: js">var kenscar = new Car('Nissan', '300ZX', 1992);
var vpgscar = new Car('Mazda', 'Miata', 1990);
</pre>

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

<pre class="brush: js">function Person(name, age, sex) {
  this.name = name;
  this.age = age;
  this.sex = sex;
}
</pre>

<p>and then instantiate two new <code>person</code> objects as follows:</p>

<pre class="brush: js">var rand = new Person('Rand McKinnon', 33, 'M');
var ken = new Person('Ken Jones', 39, 'M');
</pre>

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

<pre class="brush: js">function Car(make, model, year, owner) {
  this.make = make;
  this.model = model;
  this.year = year;
  this.owner = owner;
}
</pre>

<p>To instantiate the new objects, you then use the following:</p>

<pre class="brush: js">var car1 = new Car('Eagle', 'Talon TSi', 1993, rand);
var car2 = new Car('Nissan', '300ZX', 1992, ken);
</pre>

<p>Notice that instead of passing a literal string or integer value when creating the new objects, the above statements pass the objects <code>rand</code> and <code>ken</code> 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:</p>

<pre class="brush: js">car2.owner.name
</pre>

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

<pre class="brush: js">car1.color = 'black';
</pre>

<p>adds a property <code>color</code> 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 <code>Car</code> object type.</p>

<h3 id="Using_the_Object.create_method">Using the <code>Object.create</code> method</h3>

<p>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.</p>

<pre class="brush: js">// 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</pre>

<h2 id="Inheritance">Inheritance</h2>

<p>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 <code>prototype</code> object of the constructor. See <a href="/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain">Inheritance and the prototype chain</a> for more information.</p>

<h2 id="Indexing_object_properties">Indexing object properties</h2>

<p>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.</p>

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

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

<h2 id="Defining_properties_for_an_object_type">Defining properties for an object type</h2>

<p>You can add a property to a previously defined object type by using the <code>prototype</code> 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 <code>color</code> property to all objects of type <code>Car</code>, and then assigns a value to the <code>color</code> property of the object <code>car1</code>.</p>

<pre class="brush: js">Car.prototype.color = null;
car1.color = 'black';
</pre>

<p>See the <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype" title="en-US/docs/JavaScript/Reference/Global Objects/Function/prototype"><code>prototype</code> property</a> of the <code>Function</code> object in the <a href="/en-US/docs/Web/JavaScript/Reference">JavaScript reference</a> for more information.</p>

<h2 id="Defining_methods">Defining methods</h2>

<p>A <em>method</em> 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 <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions">method definitions</a> for more details. An example is:</p>

<pre class="brush: js">objectName.methodname = functionName;

var myObj = {
  myMethod: function(params) {
    // ...do something
  }

  // OR THIS WORKS TOO

  myOtherMethod(params) {
    // ...do something else
  }
};
</pre>

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

<p>You can then call the method in the context of the object as follows:</p>

<pre class="brush: js">object.methodname(params);
</pre>

<p>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 <code>Car</code> objects; for example,</p>

<pre class="brush: js">function displayCar() {
  var result = 'A Beautiful ' + this.year + ' ' + this.make
    + ' ' + this.model;
  pretty_print(result);
}
</pre>

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

<p>You can make this function a method of <code>Car</code> by adding the statement</p>

<pre class="brush: js">this.displayCar = displayCar;
</pre>

<p>to the object definition. So, the full definition of <code>Car</code> would now look like</p>

<pre class="brush: js">function Car(make, model, year, owner) {
  this.make = make;
  this.model = model;
  this.year = year;
  this.owner = owner;
  this.displayCar = displayCar;
}
</pre>

<p>Then you can call the <code>displayCar</code> method for each of the objects as follows:</p>

<pre class="brush: js">car1.displayCar();
car2.displayCar();
</pre>

<h2 id="Using_this_for_object_references">Using <code>this</code> for object references</h2>

<p>JavaScript has a special keyword, <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">this</a></code>, that you can use within a method to refer to the current object. For example, suppose you have a function called <code>validate</code> that validates an object's <code>value</code> property, given the object and the high and low values:</p>

<pre class="brush: js">function validate(obj, lowval, hival) {
  if ((obj.value &lt; lowval) || (obj.value &gt; hival)) {
    alert('Invalid Value!');
  }
}
</pre>

<p>Then, you could call <code>validate</code> in each form element's <code>onchange</code> event handler, using <code>this</code> to pass it the element, as in the following example:</p>

<pre class="brush: html">&lt;input type="text" name="age" size="3"
  onChange="validate(this, 18, 99)"&gt;
</pre>

<p>In general, <code>this</code> refers to the calling object in a method.</p>

<p>When combined with the <code>form</code> property, <code>this</code> can refer to the current object's parent form. In the following example, the form <code>myForm</code> contains a <code>Text</code> object and a button. When the user clicks the button, the value of the <code>Text</code> object is set to the form's name. The button's <code>onclick</code> event handler uses <code>this.form</code> to refer to the parent form, <code>myForm</code>.</p>

<pre class="brush: html">&lt;form name="myForm"&gt;
&lt;p&gt;&lt;label&gt;Form name:&lt;input type="text" name="text1" value="Beluga"&gt;&lt;/label&gt;
&lt;p&gt;&lt;input name="button1" type="button" value="Show Form Name"
     onclick="this.form.text1.value = this.form.name"&gt;
&lt;/p&gt;
&lt;/form&gt;</pre>

<h2 id="Defining_getters_and_setters">Defining getters and setters</h2>

<p>A <a href="/en-US/docs/Web/JavaScript/Reference/Functions/get">getter</a> is a method that gets the value of a specific property. A <a href="/en-US/docs/Web/JavaScript/Reference/Functions/set">setter</a> 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.</p>

<p>The following illustrates how getters and setters could work for a user-defined object <code>o</code>.</p>

<pre class="brush: js">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
</pre>

<p>The <code>o</code> object's properties are:</p>

<ul>
 <li><code>o.a</code> — a number</li>
 <li><code>o.b</code> — a getter that returns <code>o.a</code> plus 1</li>
 <li><code>o.c</code> — a setter that sets the value of <code>o.a</code> to half of the value <code>o.c</code> is being set to</li>
</ul>

<p>Please note that function names of getters and setters defined in an object literal using "[gs]et <em>property</em>()" (as opposed to <code>__define[GS]etter__</code> ) are not the names of the getters themselves, even though the <code>[gs]et <em>propertyName</em>(){ }</code> syntax may mislead you to think otherwise. To name a function in a getter or setter using the "[gs]et <em>property</em>()" syntax, define an explicitly named function programmatically using <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Object/defineProperty" title="en-US/docs/Core JavaScript 1.5 Reference/Global
Objects/Object/defineProperty">Object.defineProperty</a></code> (or the <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Object/defineGetter" title="en-US/docs/Core JavaScript 1.5 Reference/Global
Objects/Object/defineGetter">Object.prototype.__defineGetter__</a></code> legacy fallback).</p>

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

<p>These statements define a getter and setter for the year property:</p>

<pre class="brush: js">var d = Date.prototype;
Object.defineProperty(d, 'year', {
  get: function() { return this.getFullYear(); },
  set: function(y) { this.setFullYear(y); }
});
</pre>

<p>These statements use the getter and setter in a <code>Date</code> object:</p>

<pre class="brush: js">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
</pre>

<p>In principle, getters and setters can be either</p>

<ul>
 <li>defined using <a href="#Object_initializers">object initializers</a>, or</li>
 <li>added later to any object at any time using a getter or setter adding method.</li>
</ul>

<p>When defining getters and setters using <a href="#Object_initializers">object initializers</a> all you need to do is to prefix a getter method with <code>get</code> and a setter method with <code>set</code>. 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:</p>

<pre class="brush: js">var o = {
  a: 7,
  get b() { return this.a + 1; },
  set c(x) { this.a = x / 2; }
};
</pre>

<p>Getters and setters can also be added to an object at any time after creation using the <code>Object.defineProperties</code> 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:</p>

<pre class="brush: js">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
</pre>

<p>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.</p>

<h2 id="Deleting_properties">Deleting properties</h2>

<p>You can remove a non-inherited property by using the <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/delete">delete</a></code> operator. The following code shows how to remove a property.</p>

<pre class="brush: js">// 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); // yields "false"
</pre>

<p>You can also use <code>delete</code> to delete a global variable if the <code>var</code> keyword was not used to declare the variable:</p>

<pre class="brush: js">g = 17;
delete g;
</pre>

<h2 id="Comparing_Objects">Comparing Objects</h2>

<p>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.</p>

<pre class="brush: js">// 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</pre>

<pre class="brush: js">// 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
</pre>

<pre class="brush: js">fruit.name = 'grape';
console.log(fruitbear);    // yields { name: "grape" } instead of { name: "apple" }
</pre>

<p>For more information about comparison operators, see <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators">Comparison operators</a>.</p>

<h2 id="See_also">See also</h2>

<ul>
 <li>To dive deeper, read about the <a href="/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model">details of javaScript's objects model</a>.</li>
 <li>To learn about ECMAScript 2015 classes (a new way to create objects), read the <a href="/en-US/docs/Web/JavaScript/Reference/Classes">JavaScript classes</a> chapter.</li>
</ul>

<p>{{PreviousNext("Web/JavaScript/Guide/Regular_Expressions", "Web/JavaScript/Guide/Feinheiten_des_Objektmodells")}}</p>