From 4b1a9203c547c019fc5398082ae19a3f3d4c3efe Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:41:15 -0500 Subject: initial commit --- .../javascript/bausteine/ereignisse/index.html | 587 ++++++++++++++++++ files/de/learn/javascript/bausteine/index.html | 42 ++ .../javascript/first_steps/erster_blick/index.html | 597 +++++++++++++++++++ files/de/learn/javascript/first_steps/index.html | 67 +++ .../lustige_geschichten_generator/index.html | 139 +++++ .../first_steps/useful_string_methods/index.html | 656 +++++++++++++++++++++ .../javascript/first_steps/variables/index.html | 386 ++++++++++++ .../first_steps/was_ist_javascript/index.html | 339 +++++++++++ files/de/learn/javascript/index.html | 47 ++ .../de/learn/javascript/objects/basics/index.html | 258 ++++++++ files/de/learn/javascript/objects/index.html | 53 ++ .../javascript/objects/inheritance/index.html | 440 ++++++++++++++ files/de/learn/javascript/objects/json/index.html | 345 +++++++++++ .../objects/object-oriented_js/index.html | 290 +++++++++ .../objects/object_prototypes/index.html | 288 +++++++++ 15 files changed, 4534 insertions(+) create mode 100644 files/de/learn/javascript/bausteine/ereignisse/index.html create mode 100644 files/de/learn/javascript/bausteine/index.html create mode 100644 files/de/learn/javascript/first_steps/erster_blick/index.html create mode 100644 files/de/learn/javascript/first_steps/index.html create mode 100644 files/de/learn/javascript/first_steps/lustige_geschichten_generator/index.html create mode 100644 files/de/learn/javascript/first_steps/useful_string_methods/index.html create mode 100644 files/de/learn/javascript/first_steps/variables/index.html create mode 100644 files/de/learn/javascript/first_steps/was_ist_javascript/index.html create mode 100644 files/de/learn/javascript/index.html create mode 100644 files/de/learn/javascript/objects/basics/index.html create mode 100644 files/de/learn/javascript/objects/index.html create mode 100644 files/de/learn/javascript/objects/inheritance/index.html create mode 100644 files/de/learn/javascript/objects/json/index.html create mode 100644 files/de/learn/javascript/objects/object-oriented_js/index.html create mode 100644 files/de/learn/javascript/objects/object_prototypes/index.html (limited to 'files/de/learn/javascript') diff --git a/files/de/learn/javascript/bausteine/ereignisse/index.html b/files/de/learn/javascript/bausteine/ereignisse/index.html new file mode 100644 index 0000000000..c07922c124 --- /dev/null +++ b/files/de/learn/javascript/bausteine/ereignisse/index.html @@ -0,0 +1,587 @@ +--- +title: Einleitung der Ereignissen +slug: Learn/JavaScript/Bausteine/Ereignisse +translation_of: Learn/JavaScript/Building_blocks/Events +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Return_values","Learn/JavaScript/Building_blocks/Image_gallery", "Learn/JavaScript/Building_blocks")}}
+ +

Events oder auch Ereignisse sind Vorfälle die im System ausgelöst werden können. Auf diese Events wird vom System aufmerksam gemacht und es ust  möglich, in irgendeiner Art und Weise darauf zu reagieren.
+ Ein Beispiel: Ein Benutzer klickt einen Knopf auf der Website, woraufhin eine Box mit Infromationen eingeblendet wird.
+ In diesem Artikel besprechen wir einige wichtige Konzepte rund um  die Events und deren Funktionsweise im Browser. Wir werden hierbei nicht auf jedes Detail eingehen und nur das bis zum jetzigen Wissensstandpunkt nötigste abdecken.

+ + + + + + + + + + + + +
Prerequisites:Basic computer literacy, a basic understanding of HTML and CSS, JavaScript first steps.
Objective:To understand the fundamental theory of events, how they work in browsers, and how events may differ in different programming environments.
+ +

A series of fortunate events

+ +

As mentioned above, events are actions or occurrences that happen in the system you are programming — the system produces (or "fires") a signal of some kind when an event occurs, and also provides a mechanism by which some kind of action can be automatically taken (that is, some code running) when the event occurs. For example in an airport when the runway is clear for a plane to take off, a signal is communicated to the pilot, and as a result, they commence piloting the plane.

+ +

+ +

In the case of the Web, events are fired inside the browser window, and tend to be attached to a specific item that resides in it — this might be a single element, set of elements, the HTML document loaded in the current tab, or the entire browser window. There are a lot of different types of events that can occur, for example:

+ + + +

You can gather from this (and from glancing at the MDN Event reference) that there are a lot of events that can be responded to.

+ +

Each available event has an event handler, which is a block of code (usually a JavaScript function that you as a programmer create) that will be run when the event fires. When such a block of code is defined to be run in response to an event firing, we say we are registering an event handler. Note that event handlers are sometimes called event listeners — they are pretty much interchangeable for our purposes, although strictly speaking, they work together. The listener listens out for the event happening, and the handler is the code that is run in response to it happening.

+ +
+

Note: Web events are not part of the core JavaScript language — they are defined as part of the APIs built into the browser.

+
+ +

A simple example

+ +

Let's look at a simple example to explain what we mean here. You've already seen events and event handlers used in many of the examples in this course already, but let's recap just to cement our knowledge. In the following example, we have a single {{htmlelement("button")}}, which when pressed, makes the background change to a random color:

+ +
<button>Change color</button>
+ + + +

The JavaScript looks like so:

+ +
const btn = document.querySelector('button');
+
+function random(number) {
+  return Math.floor(Math.random() * (number+1));
+}
+
+btn.onclick = function() {
+  const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
+  document.body.style.backgroundColor = rndCol;
+}
+ +

In this code, we store a reference to the button inside a constant called btn, using the {{domxref("Document.querySelector()")}} function. We also define a function that returns a random number. The third part of the code is the event handler. The btn constant points to a <button> element, and this type of object has a number of events that can fire on it, and therefore, event handlers available. We are listening for the click event firing, by setting the onclick event handler property to equal an anonymous function containing code that generates a random RGB color and sets the <body> background-color equal to it.

+ +

This code is run whenever the click event fires on the <button> element, that is, whenever a user clicks on it.

+ +

The example output is as follows:

+ +

{{ EmbedLiveSample('A_simple_example', '100%', 200, "", "", "hide-codepen-jsfiddle") }}

+ +

It's not just web pages

+ +

Another thing worth mentioning at this point is that events are not unique to JavaScript — most programming languages have some kind of event model, and the way the model works often differs from JavaScript's way. In fact, the event model in JavaScript for web pages differs from the event model for JavaScript as it is used in other environments.

+ +

For example, Node.js is a very popular JavaScript runtime that enables developers to use JavaScript to build network and server-side applications. The Node.js event model relies on listeners to listen for events and emitters to emit events periodically — it doesn't sound that different, but the code is quite different, making use of functions like on() to register an event listener, and once() to register an event listener that unregisters after it has run once. The HTTP connect event docs provide a good example of use.

+ +

As another example, you can also use JavaScript to build cross-browser add-ons — browser functionality enhancements — using a technology called WebExtensions. The event model is similar to the web events model, but a bit different — event listeners properties are camel-cased (such as onMessage rather than onmessage), and need to be combined with the addListener function. See the runtime.onMessage page for an example.

+ +

You don't need to understand anything about other such environments at this stage in your learning; we just wanted to make it clear that events can differ in different programming environments.

+ +

Ways of using web events

+ +

There are a number of ways in which you can add event listener code to web pages so that it will be run when the associated event fires. In this section, we review the various mechanisms and discuss which ones you should use.

+ +

Event handler properties

+ +

These are the properties that exist to contain event handler code that we have seen most frequently during the course. Returning to the above example:

+ +
const btn = document.querySelector('button');
+
+btn.onclick = function() {
+  const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
+  document.body.style.backgroundColor = rndCol;
+}
+ +

The onclick property is the event handler property being used in this situation. It is essentially a property like any other available on the button (e.g. btn.textContent, or btn.style), but it is a special type — when you set it to be equal to some code, that code is run when the event fires on the button.

+ +

You could also set the handler property to be equal to a named function name (like we saw in Build your own function). The following would work just the same:

+ +
const btn = document.querySelector('button');
+
+function bgChange() {
+  const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
+  document.body.style.backgroundColor = rndCol;
+}
+
+btn.onclick = bgChange;
+ +

There are many different event handler properties available. Let's do an experiment.

+ +

First of all, make a local copy of random-color-eventhandlerproperty.html, and open it in your browser. It's just a copy of the simple random color example we've been playing with already in this article. Now try changing btn.onclick to the following different values in turn, and observing the results in the example:

+ + + +

Some events are very general and available nearly anywhere (for example an onclick handler can be registered on nearly any element), whereas some are more specific and only useful in certain situations (for example it makes sense to use onplay only on specific elements, such as {{htmlelement("video")}}).

+ +

Inline event handlers — don't use these

+ +

You might also see a pattern like this in your code:

+ +
<button onclick="bgChange()">Press me</button>
+
+ +
function bgChange() {
+  const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
+  document.body.style.backgroundColor = rndCol;
+}
+ +
+

Note: You can find the full source code for this example on GitHub (also see it running live).

+
+ +

The earliest method of registering event handlers found on the Web involved event handler HTML attributes (or inline event handlers) like the one shown above — the attribute value is literally the JavaScript code you want to run when the event occurs. The above example invokes a function defined inside a {{htmlelement("script")}} element on the same page, but you could also insert JavaScript directly inside the attribute, for example:

+ +
<button onclick="alert('Hello, this is my old-fashioned event handler!');">Press me</button>
+ +

You can find HTML attribute equivalents for many of the event handler properties; however, you shouldn't use these — they are considered bad practice. It might seem easy to use an event handler attribute if you are just doing something really quick, but they very quickly become unmanageable and inefficient.

+ +

For a start, it is not a good idea to mix up your HTML and your JavaScript, as it becomes hard to parse — keeping your JavaScript all in one place is better; if it is in a separate file you can apply it to multiple HTML documents.

+ +

Even in a single file, inline event handlers are not a good idea. One button is OK, but what if you had 100 buttons? You'd have to add 100 attributes to the file; it would very quickly turn into a maintenance nightmare. With JavaScript, you could easily add an event handler function to all the buttons on the page no matter how many there were, using something like this:

+ +
const buttons = document.querySelectorAll('button');
+
+for (let i = 0; i < buttons.length; i++) {
+  buttons[i].onclick = bgChange;
+}
+ +

Note that another option here would be to use the forEach() built-in method available on NodeList objects:

+ +
buttons.forEach(function(button) {
+  button.onclick = bgChange;
+});
+ +
+

Note: Separating your programming logic from your content also makes your site more friendly to search engines.

+
+ +

addEventListener() and removeEventListener()

+ +

The newest type of event mechanism is defined in the Document Object Model (DOM) Level 2 Events Specification, which provides browsers with a new function — addEventListener(). This functions in a similar way to the event handler properties, but the syntax is obviously different. We could rewrite our random color example to look like this:

+ +
const btn = document.querySelector('button');
+
+function bgChange() {
+  const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
+  document.body.style.backgroundColor = rndCol;
+}
+
+btn.addEventListener('click', bgChange);
+ +
+

Note: You can find the full source code for this example on GitHub (also see it running live).

+
+ +

Inside the addEventListener() function, we specify two parameters — the name of the event we want to register this handler for, and the code that comprises the handler function we want to run in response to it. Note that it is perfectly appropriate to put all the code inside the addEventListener() function, in an anonymous function, like this:

+ +
btn.addEventListener('click', function() {
+  var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
+  document.body.style.backgroundColor = rndCol;
+});
+ +

This mechanism has some advantages over the older mechanisms discussed earlier. For a start, there is a counterpart function, removeEventListener(), which removes a previously added listener. For example, this would remove the listener set in the first code block in this section:

+ +
btn.removeEventListener('click', bgChange);
+ +

This isn't significant for simple, small programs, but for larger, more complex programs it can improve efficiency to clean up old unused event handlers. Plus, for example, this allows you to have the same button performing different actions in different circumstances — all you have to do is add or remove event handlers as appropriate.

+ +

Second, you can also register multiple handlers for the same listener. The following two handlers wouldn't both be applied:

+ +
myElement.onclick = functionA;
+myElement.onclick = functionB;
+ +

The second line overwrites the value of onclick set by the first line. This would work, however:

+ +
myElement.addEventListener('click', functionA);
+myElement.addEventListener('click', functionB);
+ +

Both functions would now run when the element is clicked.

+ +

In addition, there are a number of other powerful features and options available with this event mechanism. These are a little out of scope for this article, but if you want to read up on them, have a look at the addEventListener() and removeEventListener() reference pages.

+ +

What mechanism should I use?

+ +

Of the three mechanisms, you definitely shouldn't use the HTML event handler attributes — these are outdated, and bad practice, as mentioned above.

+ +

The other two are relatively interchangeable, at least for simple uses:

+ + + +

The main advantages of the third mechanism are that you can remove event handler code if needed, using removeEventListener(), and you can add multiple listeners of the same type to elements if required. For example, you can call addEventListener('click', function() { ... }) on an element multiple times, with different functions specified in the second argument. This is impossible with event handler properties because any subsequent attempts to set a property will overwrite earlier ones, e.g.:

+ +
element.onclick = function1;
+element.onclick = function2;
+etc.
+ +
+

Note: If you are called upon to support browsers older than Internet Explorer 8 in your work, you may run into difficulties, as such ancient browsers use different event models from newer browsers. But never fear, most JavaScript libraries (for example jQuery) have built-in functions that abstract away cross-browser differences. Don't worry about this too much at this stage in your learning journey.

+
+ +

Other event concepts

+ +

In this section, we briefly cover some advanced concepts that are relevant to events. It is not important to understand these concepts fully at this point, but they might serve to explain some code patterns you'll likely come across from time to time.

+ +

Event objects

+ +

Sometimes inside an event handler function, you might see a parameter specified with a name such as event, evt, or simply e. This is called the event object, and it is automatically passed to event handlers to provide extra features and information. For example, let's rewrite our random color example again slightly:

+ +
function bgChange(e) {
+  const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
+  e.target.style.backgroundColor = rndCol;
+  console.log(e);
+}
+
+btn.addEventListener('click', bgChange);
+ +
+

Note: You can find the full source code for this example on GitHub (also see it running live).

+
+ +

Here you can see that we are including an event object, e, in the function, and in the function setting a background color style on e.target — which is the button itself. The target property of the event object is always a reference to the element that the event has just occurred upon. So in this example, we are setting a random background color on the button, not the page.

+ +
+

Note: You can use any name you like for the event object — you just need to choose a name that you can then use to reference it inside the event handler function. e/evt/event are most commonly used by developers because they are short and easy to remember. It's always good to be consistent — with yourself, and with others if possible.

+
+ +

e.target is incredibly useful when you want to set the same event handler on multiple elements and do something to all of them when an event occurs on them. You might, for example, have a set of 16 tiles that disappear when they are clicked on. It is useful to always be able to just set the thing to disappear as e.target, rather than having to select it in some more difficult way. In the following example (see useful-eventtarget.html for the full source code; also see it running live here), we create 16 {{htmlelement("div")}} elements using JavaScript. We then select all of them using {{domxref("document.querySelectorAll()")}}, then loop through each one, adding an onclick handler to each that makes it so that a random color is applied to each one when clicked:

+ +
const divs = document.querySelectorAll('div');
+
+for (let i = 0; i < divs.length; i++) {
+  divs[i].onclick = function(e) {
+    e.target.style.backgroundColor = bgChange();
+  }
+}
+ +

The output is as follows (try clicking around on it — have fun):

+ + + +

{{ EmbedLiveSample('Hidden_example', '100%', 400, "", "", "hide-codepen-jsfiddle") }}

+ +

Most event handlers you'll encounter just have a standard set of properties and functions (methods) available on the event object; see the {{domxref("Event")}} object reference for a full list. Some more advanced handlers, however, add specialist properties containing extra data that they need to function. The Media Recorder API, for example, has a dataavailable event, which fires when some audio or video has been recorded and is available for doing something with (for example saving it, or playing it back). The corresponding ondataavailable handler's event object has a data property available containing the recorded audio or video data to allow you to access it and do something with it.

+ +

Preventing default behavior

+ +

Sometimes, you'll come across a situation where you want to prevent an event from doing what it does by default. The most common example is that of a web form, for example, a custom registration form. When you fill in the details and press the submit button, the natural behavior is for the data to be submitted to a specified page on the server for processing, and the browser to be redirected to a "success message" page of some kind (or the same page, if another is not specified.)

+ +

The trouble comes when the user has not submitted the data correctly — as a developer, you want to prevent the submission to the server and give an error message saying what's wrong and what needs to be done to put things right. Some browsers support automatic form data validation features, but since many don't, you are advised to not rely on those and implement your own validation checks. Let's look at a simple example.

+ +

First, a simple HTML form that requires you to enter your first and last name:

+ +
<form>
+  <div>
+    <label for="fname">First name: </label>
+    <input id="fname" type="text">
+  </div>
+  <div>
+    <label for="lname">Last name: </label>
+    <input id="lname" type="text">
+  </div>
+  <div>
+     <input id="submit" type="submit">
+  </div>
+</form>
+<p></p>
+ + + +

Now some JavaScript — here we implement a very simple check inside an onsubmit event handler (the submit event is fired on a form when it is submitted) that tests whether the text fields are empty. If they are, we call the preventDefault() function on the event object — which stops the form submission — and then display an error message in the paragraph below our form to tell the user what's wrong:

+ +
const form = document.querySelector('form');
+const fname = document.getElementById('fname');
+const lname = document.getElementById('lname');
+const para = document.querySelector('p');
+
+form.onsubmit = function(e) {
+  if (fname.value === '' || lname.value === '') {
+    e.preventDefault();
+    para.textContent = 'You need to fill in both names!';
+  }
+}
+ +

Obviously, this is pretty weak form validation — it wouldn't stop the user validating the form with spaces or numbers entered into the fields, for example — but it is OK for example purposes. The output is as follows:

+ +

{{ EmbedLiveSample('Preventing_default_behavior', '100%', 140, "", "", "hide-codepen-jsfiddle") }}

+ +
+

Note: for the full source code, see preventdefault-validation.html (also see it running live here.)

+
+ +

Event bubbling and capture

+ +

The final subject to cover here is something that you won't come across often, but it can be a real pain if you don't understand it. Event bubbling and capture are two mechanisms that describe what happens when two handlers of the same event type are activated on one element. Let's look at an example to make this easier — open up the show-video-box.html example in a new tab (and the source code in another tab.) It is also available live below:

+ + + +

{{ EmbedLiveSample('Hidden_video_example', '100%', 500, "", "", "hide-codepen-jsfiddle") }}

+ +

This is a pretty simple example that shows and hides a {{htmlelement("div")}} with a {{htmlelement("video")}} element inside it:

+ +
<button>Display video</button>
+
+<div class="hidden">
+  <video>
+    <source src="rabbit320.mp4" type="video/mp4">
+    <source src="rabbit320.webm" type="video/webm">
+    <p>Your browser doesn't support HTML5 video. Here is a <a href="rabbit320.mp4">link to the video</a> instead.</p>
+  </video>
+</div>
+ +

When the {{htmlelement("button")}} is clicked, the video is displayed, by changing the class attribute on the <div> from hidden to showing (the example's CSS contains these two classes, which position the box off the screen and on the screen, respectively):

+ +
btn.onclick = function() {
+  videoBox.setAttribute('class', 'showing');
+}
+ +

We then add a couple more onclick event handlers — the first one to the <div> and the second one to the <video>. The idea is that when the area of the <div> outside the video is clicked, the box should be hidden again; when the video itself is clicked, the video should start to play.

+ +
videoBox.onclick = function() {
+  videoBox.setAttribute('class', 'hidden');
+};
+
+video.onclick = function() {
+  video.play();
+};
+ +

But there's a problem — currently, when you click the video it starts to play, but it causes the <div> to also be hidden at the same time. This is because the video is inside the <div> — it is part of it — so clicking on the video actually runs both the above event handlers.

+ +

Bubbling and capturing explained

+ +

When an event is fired on an element that has parent elements (in this case, the {{htmlelement("video")}} has the {{htmlelement("div")}} as a parent), modern browsers run two different phases — the capturing phase and the bubbling phase.

+ +

In the capturing phase:

+ + + +

In the bubbling phase, the exact opposite occurs:

+ + + +

+ +

(Click on image for bigger diagram)

+ +

In modern browsers, by default, all event handlers are registered for the bubbling phase. So in our current example, when you click the video, the click event bubbles from the <video> element outwards to the <html> element. Along the way:

+ + + +
+

Note: In cases where both types of event handlers are present, bubbling and capturing, the capturing phase will run first, followed by the bubbling phase.

+
+ +

Fixing the problem with stopPropagation()

+ +

This is annoying behavior, but there is a way to fix it! The standard Event object has a function available on it called stopPropagation() which, when invoked on a handler's event object, makes it so that first handler is run but the event doesn't bubble any further up the chain, so no more handlers will be run.

+ +

We can, therefore, fix our current problem by changing the second handler function in the previous code block to this:

+ +
video.onclick = function(e) {
+  e.stopPropagation();
+  video.play();
+};
+ +

You can try making a local copy of the show-video-box.html source code and fixing it yourself, or looking at the fixed result in show-video-box-fixed.html (also see the source code here).

+ +
+

Note: Why bother with both capturing and bubbling? Well, in the bad old days when browsers were much less cross-compatible than they are now, Netscape only used event capturing, and Internet Explorer used only event bubbling. When the W3C decided to try to standardize the behavior and reach a consensus, they ended up with this system that included both, which is the one modern browsers implemented.

+
+ +
+

Note: As mentioned above, by default all event handlers are registered in the bubbling phase, and this makes more sense most of the time. If you really want to register an event in the capturing phase instead, you can do so by registering your handler using addEventListener(), and setting the optional third property to true.

+
+ +

Event delegation

+ +

Bubbling also allows us to take advantage of event delegation — this concept relies on the fact that if you want some code to run when you click on any one of a large number of child elements, you can set the event listener on their parent and have events that happen on them bubble up to their parent rather than having to set the event listener on every child individually. Remember earlier that we said bubbling involves checking the element the event is fired on for an event handler first, then moving up to the element's parent, etc.?

+ +

A good example is a series of list items — if you want each one of them to pop up a message when clicked, you can set the click event listener on the parent <ul>, and events will bubble from the list items to the <ul>.

+ +

This concept is explained further on David Walsh's blog, with multiple examples — see How JavaScript Event Delegation Works.

+ +

Test your skills!

+ +

You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see Test your skills: Events.

+ +

Conclusion

+ +

You should now know all you need to know about web events at this early stage. As mentioned above, events are not really part of the core JavaScript — they are defined in browser Web APIs.

+ +

Also, it is important to understand that the different contexts in which JavaScript is used have different event models — from Web APIs to other areas such as browser WebExtensions and Node.js (server-side JavaScript). We are not expecting you to understand all these areas now, but it certainly helps to understand the basics of events as you forge ahead with learning web development.

+ +

If there is anything you didn't understand, feel free to read through the article again, or contact us to ask for help.

+ +

See also

+ + + +

{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Return_values","Learn/JavaScript/Building_blocks/Image_gallery", "Learn/JavaScript/Building_blocks")}}

+ +

In this module

+ + diff --git a/files/de/learn/javascript/bausteine/index.html b/files/de/learn/javascript/bausteine/index.html new file mode 100644 index 0000000000..1c6fb8fc46 --- /dev/null +++ b/files/de/learn/javascript/bausteine/index.html @@ -0,0 +1,42 @@ +--- +title: JavaScript Bausteine +slug: Learn/JavaScript/Bausteine +translation_of: Learn/JavaScript/Building_blocks +--- +
{{LearnSidebar}}
+ +

In diesem Modul betrachten wir weiterhin JavaScripts Kernfunktionen. Wir betrachten verschiedene, häufig vorkommende Arten von Code Blöcken, wie zum Beispiel Fallunterscheidungen, Schleifen, Funktionen und Events. Diese hast du bereits im Laufe des Kurses gesehen, allerdings nur "nebenbei" -  jetzt behandeln wir sie explizit.

+ +

Vorraussetzungen

+ +

Bevor du mit diesem Modul anfängst, solltest du mit den Grundlagen von HTML und CSS vertraut sein und das vorherige Modul, Erste Schritte mit JavaScript, abgeschlossen haben.

+ +
+

Hinweis: Falls du auf einem Computer/Tablet/anderem Gerät arbeitest, auf dem du keine Dateien erstellen kannst, kannst du die (meisten) Code Beispiele online, zum Beispiel mit JSBin oder Thimble, ausprobieren.

+
+ +

Anleitungen

+ +
+
Entscheidungen treffen --- Fallunterscheidungen
+
In allen Programmiersprachen muss Code Entscheidungen treffen und bei unterschiedlichen Eingaben entsprechend handeln. Falls zum Beispiel in einem Spiel der Spieler keine Leben mehr übrig hat, so hat er das Spiel verloren. In einer Wetter-App soll beispielsweise morgens ein Sonnenaufgang als Hintergrund gezeigt werden, nachts jedoch Mond und Sterne. In diesem Artikel betrachten wir Fallunterscheidungen und wie diese in JavaScript funktionieren.
+
Code wiederholen
+
Manchmal soll eine Aufgabe mehr als einmal ausgeführt werden, zum Beispiel wenn eine Liste an Namen durchsucht wird. Um solche Aufgaben zu erledigen, sind Schleifen eine gute Lösung. Im folgenden Artikel werden wir Schleifen in JavaScript genauer betrachten.
+
Funktionen -- Wiederverwendbare Codeblöcke
+
Ein essentielles Konzept in der Programmierung sind Funktionen. Funktionen erlauben es, Code, der eine bestimmte Aufgabe erfüllt, in einem eigenen Block zu definieren. Anschließend kann dieser Code über ein einzelnes, kurzes Kommando aufgerufen werden, anstatt den ganzen Code mehrere Male tippen zu müssen. In diesem Artikel erkunden wir die Konzepte hinter Funktionen wie die grundlegende Syntax oder wie diese aufgerufen werden und definieren die Begriffe Funktion, Sichtbereich (Scope) und Parameter.
+
Baue deine eigene Funktion
+
Nach dem der Großteil der grundlegenden Theorie im vorherigen Artikel thematisiert wurde, bietet dieser Artikel eine praktische Erfahrung. Hier bekommst du etwas Übung im Erstellen deiner eigenen Funktion. Außerdem werden wir einige weitere nützliche Details für das Arbeiten mit Funktionen behandeln. 
+
Rückgabewerte von Funktionen
+
Es gibt ein weiteres essentielles Konzept, dass wir in diesem Kurs behandeln werden, um unsere Betrachtung von Funktionne abzuschließen --- Rückgabewerte. Manche Funktionen geben keinen "sinnvollen" Wert zurück, andere schon. Es ist wichtig zu verstehen, was diese Werte sind, wie sie benutzt werden und wie du Funktionen schreibst, die sinnvolle Werte zurückgeben.
+
Einführung in Events
+
Events sind Aktionen oder Ereignisse die in dem System, in dem du programmierts, passieren. Das System weist dich auf diese hin, so dass du gegebenenfalls entsprechend reagieren kannst. Klickt ein Nutzer beispielsweise auf einen Button auf einer Webseite, so möchtest du vermutlich darauf reagieren, in dem du eine Aktion ausführst. In diesem Artikel behandeln wir einige wichtige Konzepte bezüglich Events und betrachten deren Funktionsweise in Browsern.
+
+ +

Prüfungen

+ +

Die folgenden Aufgaben werden dein Verständnis der in diesen Artikeln behandelten JavaScript Grundlagen prüfen. 

+ +
+
Bildergalerie
+
Jetzt wo wir die grundlegenden Bausteine JavaScripts betrachtet haben, werden wir dein Wissen über Schleifen, Funktionen, Fallunterscheidungen und Events testen, indem wir eine JavaScript-basierte Bildergalerie entwickeln.
+
diff --git a/files/de/learn/javascript/first_steps/erster_blick/index.html b/files/de/learn/javascript/first_steps/erster_blick/index.html new file mode 100644 index 0000000000..e772147cae --- /dev/null +++ b/files/de/learn/javascript/first_steps/erster_blick/index.html @@ -0,0 +1,597 @@ +--- +title: Ein erster Eindruck von JavaScript +slug: Learn/JavaScript/First_steps/Erster_Blick +translation_of: Learn/JavaScript/First_steps/A_first_splash +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/First_steps/What_is_JavaScript", "Learn/JavaScript/First_steps/What_went_wrong", "Learn/JavaScript/First_steps")}}
+ +

Nachdem Sie etwas über die Theorie von JavaScript gelernt haben und was Sie damit machen können, werden wir Ihnen in einem komplett praktischen Tutorial einen Crashkurs in den Grundfunktionen von JavaScript anbieten. Wir werden hier Schritt für Schritt ein einfaches Zahlenraten Spiel programmieren.

+ + + + + + + + + + + + +
Voraussetzungen:Grundlegende Computerkenntnisse, einfache Grundkentnisse von HTML und CSS, sowie eine Vorstellung, was JavaScript ist.
Ziel:Erste Erfahrung beim Schreiben von JavaScript zu bekommen und zumindest ein grundlegendes Verständnis dafür zu erlangen, was das Schreiben eines JavaScript-Programms beinhaltet.
+ +

Es ist nicht nötig, dass Sie den gesamten Code sofort im Detail verstehen - wir wollen Ihnen nur grob die Konzepte vorab vorstellen und Ihnen eine Vorstellung davon vermitteln, wie JavaScript (und andere Programmiersprachen) funktionieren. In den folgenden Artikeln werden wir alle diese Funktionen noch einmal im Detail besprechen!

+ +
+

Hinweis: Viele der Befehle und Konstrukte, die Sie in JavaScript sehen werden, sind die gleichen wie in anderen Programmiersprachen - Funktionen, Schleifen, etc. Die Syntax sieht anders aus, aber die Konzepte sind immer noch weitgehend die gleichen.

+
+ +

Denken wie ein Programmierer

+ +

Eines der schwierigsten Dinge, die man bei der Programmierung lernen muss, sind nicht die Befehle, sondern wie man sie zur Lösung der Aufgabe anwendet. Sie müssen anfangen, wie ein Programmierer zu denken - Sie müssen sich im klaren sein was  Ihr Programm tun soll, um dann herauszuarbeiten welche Funktionen und Befehle Sie dafür benötigen.

+ +

Dies erfordert eine Mischung aus harter Arbeit, Erfahrung mit der Programmiersprache und Praxis - und ein wenig Kreativität. Je mehr Sie kodieren, desto besser werden Sie werden. Wir können nicht versprechen, dass Sie in fünf Minuten ein "Programmierer-Gehirn" entwickeln werden, aber wir werden Ihnen viel Gelegenheit geben, während des gesamten Kurses das Denken wie ein Programmierer zu üben.

+ +

In diesem Sinne betrachten Sie das Beispiel, das wir in diesem Artikel erstellen werden und üben damit den Prozess der Zerlegung in konkrete Einzelschritte.

+ +

Beispiel — Rate die Zahl

+ +

In diesem Artikel zeigen wir Ihnen, wie Sie das Ratespiel aufbauen können, das Sie hier sehen können.:

+ + + +

{{ EmbedLiveSample('Top_hidden_code', '100%', 320, "", "", "hide-codepen-jsfiddle") }}

+ +

Machen Sie sich mit der Funktionsweise des Spiels vertraut, bevor Sie weitermachen.

+ +

Stellen wir uns vor, Ihr Chef hat Ihnen den folgenden Auftrag für die Erstellung dieses Spiels gegeben:

+ +
+

Schreiben Sie ein Programm das ein Zahlenratespiel implementiert. Es sollte eine Zufallszahl zwischen 1 und 100 wählen und den Spieler auffordern, die Zahl nach spätestens 10 Runden zu erraten. Nach jedem Zug sollte dem Spieler mitgeteilt werden, ob er richtig geraten hat oder nicht - und, wenn er Unrecht hat, ob die Zahl zu niedrig oder zu hoch war. Außerdem sollen dem Spieler alle vorher geratenen Zahlen angezeigt werden. Das Spiel endet, wenn der Spieler richtig rät oder wenn er 10-mal falsch geraten hat. Wenn das Spiel endet, sollte dem Spieler die Möglichkeit gegeben werden, erneut zu spielen.

+
+ +

Wenn wir uns diesen Anweisungen ansehen, können wir zunächst damit beginnen, ihn in einfache, umsetzbare Aufgaben aufzuteilen, und zwar aus der Sicht eines Programmierers:

+ +
    +
  1. Generiere eine zufällige Zahl zwischen 1 und 100.
  2. +
  3. Speichere die Anzahl der getätigten Rateversuche, setze den Wert anfangs auf 1.
  4. +
  5. Ermögliche dem Spieler, einen Tipp abzugeben.
  6. +
  7. Sobald ein Tip abgegeben wurde, speichere sie damit der Spieler seine vorherigen Eingaben sehen kann.
  8. +
  9. Als Nächstes überprüfe, ob es sich um die richtige Zahl handelt.
  10. +
  11. Wenn sie richtig ist: +
      +
    1. Zeige Glückwunsch Nachricht.
    2. +
    3. Verhindere weiter Eingaben, da das Spiel zu Ende ist.
    4. +
    5. Biete eine Möglichkeit, das Spiel neu zu starten.
    6. +
    +
  12. +
  13. Wenn sie falsch ist und noch Versuche übrig sind: +
      +
    1. Dem Spieler mitteilen, dass die Zahl noch nicht erraten ist.
    2. +
    3. Die Eingabe einer weiteren Zahl ermöglichen.
    4. +
    5. Die Anzahl der Rateversuche um 1 erhöhen.
    6. +
    +
  14. +
  15. Wenn die Zahl falsch ist und keine Versuche mehr übrig sind: +
      +
    1. Dem Spieler mitteilen, dass das Spiel zu Ende ist.
    2. +
    3. Keine weiteren Eingaben mehr zulassen.
    4. +
    5. Ein Steuerelement zum Neustart des Spiels anzeigen.
    6. +
    +
  16. +
  17. Wenn das Spiel neu startet, sicherstellen dass Logik und Benutzeroberfläche zurückgesetzt werden. Danach zurück zum 1. Schritt.
  18. +
+ +

Lassen Sie uns nun fortfahren und schauen, wie wir diese Punkte in Code umwandeln können, das Beispiel aufbauen und die JavaScript-Funktionen während der Arbeit erforschen.

+ +

Vorbereitungen

+ +

Um dieses Tutorial zu beginnen, möchten wir Sie bitten, eine lokale Kopie der Datei number-guessing-game-start.html (see it live here) zu erstellen. Öffnen Sie es sowohl in Ihrem Texteditor als auch in Ihrem Webbrowser. Im Moment sehen Sie eine einfache Überschrift, einen Absatz mit Anweisungen und ein Formular zur Eingabe einer Schätzung, aber das Formular wird derzeit nichts tun.

+ +

Unseren gesamten Code werden wir innerhalb des {{htmlelement("script")}} Elements am Ende der HTML-Datei einfügen:

+ +
<script>
+
+  // Ihr Programm steht hier
+
+</script>
+
+ +

Variablen hinzufügen um Daten zu speichern

+ +

Lassen Sie uns anfangen. Fügen Sie zunächst die folgenden Zeilen nach dem {{htmlelement("script")}} Element ein:

+ +
let randomNumber = Math.floor(Math.random() * 100) + 1;
+
+const guesses = document.querySelector('.guesses');
+const lastResult = document.querySelector('.lastResult');
+const lowOrHi = document.querySelector('.lowOrHi');
+
+const guessSubmit = document.querySelector('.guessSubmit');
+const guessField = document.querySelector('.guessField');
+
+let guessCount = 1;
+let resetButton;
+ +

Obiger Code richtet die Variablen und Konstanten ein, die wir benötigen, um die Daten zu speichern, die unser Programm verwenden wird. Variablen sind im Grunde genommen Container für Werte (z.B. Zahlen oder Text). Sie erstellen eine Variable mit dem Schlüsselwort let (oder var) gefolgt von einem Namen für Ihre Variable (Sie werden mehr über den Unterschied zwischen den beiden Schlüsselwörtern in einem zukünftigen Artikel lesen). Konstanten werden verwendet, um Werte zu speichern, die Sie nicht ändern möchten, und werden mit dem Schlüsselwort const erstellt. In diesem Fall verwenden wir Konstanten, um Referenzen auf Teile unserer Benutzeroberfläche zu speichern; der Text in einigen von ihnen kann sich ändern, aber die referenzierten HTML-Elemente bleiben unverändert.

+ +

Sie können Ihrer Variablen oder Konstanten einen Wert mit einem Gleichheitszeichen (=) zuweisen, gefolgt von dem Wert, den Sie ihr geben möchten.

+ +

In unser Beispiel:

+ + + +
+

Note: You'll learn a lot more about variables/constants later on in the course, starting with the next article.

+
+ +

Functions

+ +

Next, add the following below your previous JavaScript:

+ +
function checkGuess() {
+  alert('I am a placeholder');
+}
+ +

Functions are reusable blocks of code that you can write once and run again and again, saving the need to keep repeating code all the time. This is really useful. There are a number of ways to define functions, but for now we'll concentrate on one simple type. Here we have defined a function by using the keyword function, followed by a name, with parentheses put after it. After that we put two curly braces ({ }). Inside the curly braces goes all the code that we want to run whenever we call the function.

+ +

When we want to run the code, we type the name of the function followed by the parentheses.

+ +

Let's try that now. Save your code and refresh the page in your browser. Then go into the developer tools JavaScript console, and enter the following line:

+ +
checkGuess();
+ +

After pressing Return/Enter, you should see an alert come up that says "I am a placeholder"; we have defined a function in our code that creates an alert whenever we call it.

+ +
+

Note: You'll learn a lot more about functions later in the course.

+
+ +

Operators

+ +

JavaScript operators allow us to perform tests, do maths, join strings together, and other such things.

+ +

If you haven't already done so, save your code, refresh the page in your browser, and open the developer tools JavaScript console. Then we can try typing in the examples shown below — type in each one from the "Example" columns exactly as shown, pressing Return/Enter after each one, and see what results they return.

+ +

First let's look at arithmetic operators, for example:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OperatorNameExample
+Addition6 + 9
-Subtraction20 - 15
*Multiplication3 * 7
/Division10 / 5
+ +

You can also use the + operator to join text strings together (in programming, this is called concatenation). Try entering the following lines, one at a time:

+ +
let name = 'Bingo';
+name;
+let hello = ' says hello!';
+hello;
+let greeting = name + hello;
+greeting;
+ +

There are also some shortcut operators available, called augmented assignment operators. For example, if you want to simply add a new text string to an existing one and return the result, you could do this:

+ +
name += ' says hello!';
+ +

This is equivalent to

+ +
name = name + ' says hello!';
+ +

When we are running true/false tests (for example inside conditionals — see {{anch("Conditionals", "below")}}) we use comparison operators. For example:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OperatorNameExample
===Strict equality (is it exactly the same?) +
+5 === 2 + 4 // false
+'Chris' === 'Bob' // false
+5 === 2 + 3 // true
+2 === '2' // false; number versus string
+
+
!==Non-equality (is it not the same?) +
+5 !== 2 + 4 // true
+'Chris' !== 'Bob' // true
+5 !== 2 + 3 // false
+2 !== '2' // true; number versus string
+
+
<Less than +
+6 < 10 // true
+20 < 10 // false
+
>Greater than +
+6 > 10 // false
+20 > 10  // true
+
+ +

Conditionals

+ +

Returning to our checkGuess() function, I think it's safe to say that we don't want it to just spit out a placeholder message. We want it to check whether a player's guess is correct or not, and respond appropriately.

+ +

At this point, replace your current checkGuess() function with this version instead:

+ +
function checkGuess() {
+  let userGuess = Number(guessField.value);
+  if (guessCount === 1) {
+    guesses.textContent = 'Previous guesses: ';
+  }
+  guesses.textContent += userGuess + ' ';
+
+  if (userGuess === randomNumber) {
+    lastResult.textContent = 'Congratulations! You got it right!';
+    lastResult.style.backgroundColor = 'green';
+    lowOrHi.textContent = '';
+    setGameOver();
+  } else if (guessCount === 10) {
+    lastResult.textContent = '!!!GAME OVER!!!';
+    setGameOver();
+  } else {
+    lastResult.textContent = 'Wrong!';
+    lastResult.style.backgroundColor = 'red';
+    if(userGuess < randomNumber) {
+      lowOrHi.textContent = 'Last guess was too low!';
+    } else if(userGuess > randomNumber) {
+      lowOrHi.textContent = 'Last guess was too high!';
+    }
+  }
+
+  guessCount++;
+  guessField.value = '';
+  guessField.focus();
+}
+ +

This is a lot of code — phew! Let's go through each section and explain what it does.

+ + + +

Events

+ +

At this point we have a nicely implemented checkGuess() function, but it won't do anything because we haven't called it yet. Ideally we want to call it when the "Submit guess" button is pressed, and to do this we need to use an event. Events are things that happen in the browser — a button being clicked, a page loading, a video playing, etc. — in response to which we can run blocks of code. The constructs that listen out for the event happening are called event listeners, and the blocks of code that run in response to the event firing are called event handlers.

+ +

Add the following line below your checkGuess() function:

+ +
guessSubmit.addEventListener('click', checkGuess);
+ +

Here we are adding an event listener to the guessSubmit button. This is a method that takes two input values (called arguments) — the type of event we are listening out for (in this case click) as a string, and the code we want to run when the event occurs (in this case the checkGuess() function). Note that we don't need to specify the parentheses when writing it inside {{domxref("EventTarget.addEventListener", "addEventListener()")}}.

+ +

Try saving and refreshing your code now, and your example should work — to a point. The only problem now is that if you guess the correct answer or run out of guesses, the game will break because we've not yet defined the setGameOver() function that is supposed to be run once the game is over. Let's add our missing code now and complete the example functionality.

+ +

Finishing the game functionality

+ +

Let's add that setGameOver() function to the bottom of our code and then walk through it. Add this now, below the rest of your JavaScript:

+ +
function setGameOver() {
+  guessField.disabled = true;
+  guessSubmit.disabled = true;
+  resetButton = document.createElement('button');
+  resetButton.textContent = 'Start new game';
+  document.body.appendChild(resetButton);
+  resetButton.addEventListener('click', resetGame);
+}
+ + + +

Now we need to define this function too! Add the following code, again to the bottom of your JavaScript:

+ +
function resetGame() {
+  guessCount = 1;
+
+  const resetParas = document.querySelectorAll('.resultParas p');
+  for (let i = 0 ; i < resetParas.length ; i++) {
+    resetParas[i].textContent = '';
+  }
+
+  resetButton.parentNode.removeChild(resetButton);
+
+  guessField.disabled = false;
+  guessSubmit.disabled = false;
+  guessField.value = '';
+  guessField.focus();
+
+  lastResult.style.backgroundColor = 'white';
+
+  randomNumber = Math.floor(Math.random() * 100) + 1;
+}
+ +

This rather long block of code completely resets everything to how it was at the start of the game, so the player can have another go. It:

+ + + +

At this point you should have a fully working (simple) game — congratulations!

+ +

All we have left to do now in this article is talk about a few other important code features that you've already seen, although you may have not realized it.

+ +

Loops

+ +

One part of the above code that we need to take a more detailed look at is the for loop. Loops are a very important concept in programming, which allow you to keep running a piece of code over and over again, until a certain condition is met.

+ +

To start with, go to your browser developer tools JavaScript console again, and enter the following:

+ +
for (let i = 1 ; i < 21 ; i++) { console.log(i) }
+ +

What happened? The numbers 1 to 20 were printed out in your console. This is because of the loop. A for loop takes three input values (arguments):

+ +
    +
  1. A starting value: In this case we are starting a count at 1, but this could be any number you like. You could replace the letter i with any name you like too, but i is used as a convention because it's short and easy to remember.
  2. +
  3. An exit condition: Here we have specified i < 21 — the loop will keep going until i is no longer less than 21. When i reaches 21, the loop will no longer run.
  4. +
  5. An incrementor: We have specified i++, which means "add 1 to i". The loop will run once for every value of i, until i reaches a value of 21 (as discussed above). In this case, we are simply printing the value of i out to the console on every iteration using {{domxref("Console.log", "console.log()")}}.
  6. +
+ +

Now let's look at the loop in our number guessing game — the following can be found inside the resetGame() function:

+ +
let resetParas = document.querySelectorAll('.resultParas p');
+for (let i = 0 ; i < resetParas.length ; i++) {
+  resetParas[i].textContent = '';
+}
+ +

This code creates a variable containing a list of all the paragraphs inside <div class="resultParas"> using the {{domxref("Document.querySelectorAll", "querySelectorAll()")}} method, then it loops through each one, removing the text content of each.

+ +

A small discussion on objects

+ +

Let's add one more final improvement before we get to this discussion. Add the following line just below the let resetButton; line near the top of your JavaScript, then save your file:

+ +
guessField.focus();
+ +

This line uses the {{domxref("HTMLElement.focus", "focus()")}} method to automatically put the text cursor into the {{htmlelement("input")}} text field as soon as the page loads, meaning that the user can start typing their first guess right away, without having to click the form field first. It's only a small addition, but it improves usability — giving the user a good visual clue as to what they've got to do to play the game.

+ +

Let's analyze what's going on here in a bit more detail. In JavaScript, everything is an object. An object is a collection of related functionality stored in a single grouping. You can create your own objects, but that is quite advanced and we won't be covering it until much later in the course. For now, we'll just briefly discuss the built-in objects that your browser contains, which allow you to do lots of useful things.

+ +

In this particular case, we first created a guessField constant that stores a reference to the text input form field in our HTML — the following line can be found amongst our declarations near the top of the code:

+ +
const guessField = document.querySelector('.guessField');
+ +

To get this reference, we used the {{domxref("document.querySelector", "querySelector()")}} method of the {{domxref("document")}} object. querySelector() takes one piece of information — a CSS selector that selects the element you want a reference to.

+ +

Because guessField now contains a reference to an {{htmlelement("input")}} element, it will now have access to a number of properties (basically variables stored inside objects, some of which can't have their values changed) and methods (basically functions stored inside objects). One method available to input elements is focus(), so we can now use this line to focus the text input:

+ +
guessField.focus();
+ +

Variables that don't contain references to form elements won't have focus() available to them. For example, the guesses constant contains a reference to a {{htmlelement("p")}} element, and the guessCount variable contains a number.

+ +

Playing with browser objects

+ +

Let's play with some browser objects a bit.

+ +
    +
  1. First of all, open up your program in a browser.
  2. +
  3. Next, open your browser developer tools, and make sure the JavaScript console tab is open.
  4. +
  5. Type in guessField and the console will show you that the variable contains an {{htmlelement("input")}} element. You'll also notice that the console autocompletes the names of objects that exist inside the execution environment, including your variables!
  6. +
  7. Now type in the following: +
    guessField.value = 'Hello';
    + The value property represents the current value entered into the text field. You'll see that by entering this command, we've changed the text in the text field!
  8. +
  9. Now try typing in guesses and pressing return. The console will show you that the variable contains a {{htmlelement("p")}} element.
  10. +
  11. Now try entering the following line: +
    guesses.value
    + The browser will return undefined, because paragraphs don't have the value property.
  12. +
  13. To change the text inside a paragraph, you need the {{domxref("Node.textContent", "textContent")}} property instead. Try this: +
    guesses.textContent = 'Where is my paragraph?';
    +
  14. +
  15. Now for some fun stuff. Try entering the below lines, one by one: +
    guesses.style.backgroundColor = 'yellow';
    +guesses.style.fontSize = '200%';
    +guesses.style.padding = '10px';
    +guesses.style.boxShadow = '3px 3px 6px black';
    + Every element on a page has a style property, which itself contains an object whose properties contain all the inline CSS styles applied to that element. This allows us to dynamically set new CSS styles on elements using JavaScript.
  16. +
+ +

Finished for now...

+ +

So that's it for building the example. You got to the end — well done! Try your final code out, or play with our finished version here. If you can't get the example to work, check it against the source code.

+ +

{{PreviousMenuNext("Learn/JavaScript/First_steps/What_is_JavaScript", "Learn/JavaScript/First_steps/What_went_wrong", "Learn/JavaScript/First_steps")}}

+ +

In this module

+ + diff --git a/files/de/learn/javascript/first_steps/index.html b/files/de/learn/javascript/first_steps/index.html new file mode 100644 index 0000000000..092a419e14 --- /dev/null +++ b/files/de/learn/javascript/first_steps/index.html @@ -0,0 +1,67 @@ +--- +title: Erste Schritte mit JavaScript +slug: Learn/JavaScript/First_steps +tags: + - Anleitung + - Arrays + - Artikel + - Aufgaben + - Einsteiger + - Felder + - JavaScript + - Landing + - Lernmodul + - Mathematik + - Operatoren + - Variablen + - Zahlen + - Zeichenketten +translation_of: Learn/JavaScript/First_steps +--- +
{{LearnSidebar}}
+ +

In unserem ersten Lernmodul zu JavaScript beantworten wir grundlegende Fragen wie »Was ist JavaScript?«, »Wie sieht es aus?« und »Was kann es?«, bevor wir Sie bei Ihren ersten praktischen Erfahrungen mit JavaScript begleiten. Danach erklären wir einige der wichtigsten Bausteine – wie etwa Variablen, Zeichenketten, Zahlen und Felder – im Detail.

+ +

Voraussetzungen

+ +

Um mit diesem Lernmodul zu beginnen, brauchen Sie keinerlei Vorwissen in Sachen JavaScript – Sie sollten aber bereits ein wenig mit HTML und CSS vertraut sein. Wir raten Ihnen daher dazu, die folgendenen Lektionen durchzuarbeiten, bevor Sie mit JavaScript loslegen:

+ + + +
+

Anmerkung: Falls Sie auf einem Computer, einem Tablet oder sonstigem Gerät arbeiten, auf dem Sie keine eigenen Dateien anlegen können, können Sie die Codebeispiele meist auch in einer Online-Coding-Umgebung wie JSBin oder Thimble ausprobieren.

+
+ +

Anleitungen

+ +
+
Was ist JavaScript?
+
Willkommen beim MDN-Einsteigerkurs zu JavaScript! In diesem ersten Artikel betrachten wir JavaScript von außen, beantworten Fragen wie »Was ist das?« und »Was macht es?«, und machen Sie mit dem Zweck von JavaScript vertraut.
+
Ein erster Abstecher zu JavaScript
+
Jetzt, da Sie ein wenig Hintergrundwissen über JavaScript und das, was Sie damit anstellen können haben, werden wir Ihnen in einem Crashkurs die wichtigsten Features von JavaScript anhand praktischer Beispiele beibringen.
+
Was lief verkehrt? JavaScript-Probleme beheben
+
Nachdem Sie im vorherigen Artikel das Spiel »Zahlen-Raten« konstruiert hatten, kann es sein, dass Sie feststellen mussten, dass es nicht funktionierte. Keine Angst – dieser Artikel soll Sie davor retten, sich wegen solcher Probleme die Haare zu raufen, indem er Ihnen einige einfache Tipps dazu gibt, wie Sie Fehler in JavaScript-Programmen finden und beheben.
+
Informationen, die Sie brauchen, speichern – Variablen
+
Nach dem Lesen der letzten paar Artikel sollten Sie nun wissen, was JavaScript ist, was es für Sie tun kann, wie Sie es in Kombination mit anderen Web-Technologien einsetzen, und wie die wichtigsten Features in etwa aussehen. In diesem Artikel werden wir uns anschauen, wie man einen der grundlegendsten Bausteine von JavaScript verwendet – Variablen.
+
Einfache Mathematik in JavaScript – Zahlen und Operatoren
+
An dieser Stelle im Kurs erörtern wir Mathematik in JavaScript – wie wir Operatoren und andere Features verwenden können, um Zahlen erfolgreich dazu zu bringen, zu tun, was wir wollen.
+
Text verarbeiten – Zeichenketten in JavaScript
+
Als Nächstes richten wir unsere Aufmerksamkeit auf Zeichenketten – so nennt man Textschnippsel in der Programmierung. In diesem Artikel werden wir uns häufig benötigtes Wissen zu Zeichenketten ansehen, etwa wie man sie erstellt, wie man Anführungszeichen in Zeichenketten maskiert und wie man Zeichenketten aneinanderhängt.
+
Nützliche Zeichenketten-Methoden
+
Nachdem wir uns jetzt die Grundlagen von Zeichenketten angeeignet haben, schalten wir einen Gang hoch und überlegen uns, welche nützlichen Operationen wir mit den eingebauten Methoden auf Zeichenketten ausführen können: die Länge einer Zeichenkette festellen, Zeichenketten verknüpfen und aufteilen, ein Zeichen in einer Zeichenkette durch ein anderes ersetzen, und weitere.
+
Felder
+
Im letzten Artikel dieses Lernmoduls betrachten wir Felder – ein sauberer Weg, um eine Liste von Datenelementen unter einem einzigen Variablennamen abzulegen. Wir schauen uns an, warum das nützlich ist, und erforschen dann, wie man ein Feld anlegt, Elemente, die darin gespeichert sind, abruft, hinzufügt und entfernt, und vieles mehr.
+
+ +

Aufgaben

+ +

Die folgenden Aufgaben werden Ihr Verständnis der JavaScript-Grundlagen aus den vorherigen Anleitungen überprüfen.

+ +
+
Lustige Geschichten erzeugen
+
In dieser Aufgabe sollen Sie einen Teil des Wissens, das Sie erworben haben, einsetzen, um eine spaßige Anwendung zu entwickeln, die zufällige, lustige Geschichten erzeugt. Viel Spaß!
+
diff --git a/files/de/learn/javascript/first_steps/lustige_geschichten_generator/index.html b/files/de/learn/javascript/first_steps/lustige_geschichten_generator/index.html new file mode 100644 index 0000000000..1703f9b6a7 --- /dev/null +++ b/files/de/learn/javascript/first_steps/lustige_geschichten_generator/index.html @@ -0,0 +1,139 @@ +--- +title: Der Lustige Geschichten Generator +slug: Learn/JavaScript/First_steps/lustige_geschichten_generator +translation_of: Learn/JavaScript/First_steps/Silly_story_generator +--- +
{{LearnSidebar}}
+ +
{{PreviousMenu("Learn/JavaScript/First_steps/Arrays", "Learn/JavaScript/First_steps")}}
+ +

In dieser Prüfung ist es deine Aufgabe das von dir in den vorherigen Artikeln gesammelten Wissen anzuwenden, indem due eine lustige Applikation schreibst, mit der man lustige Geschichten erzeugen kann. Viel Spass mit dem Lustige Geschichten Generator !

+ + + + + + + + + + + + +
Vorraussetzungen:Bevor du dich an dieser Aufgabe versuchst, solltest du alle anderen Artikel dieses Moduls gelesen und bearbeitet haben.
Ziel:Verständnis von fundamentalen JavaScript Kenntnissen, wie Variablen, Operatoren und einfachen Datentypen (Zahlen, Zeichenketten, Arrays)
+ +

Start

+ +

Um mit deiner Aufgabe zu beginnen, solltest du::

+ + + +
+

Notiz: Alternativ kannst du auch eine Seite wie JSBin oder Glitch benutzen, um die Aufgabe zu bearbeiten. Kopiere dazu einfach den Quelltext von HTML, CSS und JavaScript in einen dieser Online-Editoren. Wenn einer dieser Editoren kein extra JavaScript Panel haben sollte, kopiere das JavaScript einfach zwischen <script>-Tags in deinem HTML-Code.

+
+ +

Projektbeschreibung

+ +

Für diese Aufgabe geben wir dir einige HTML/CSS Codestücke, einige Textbausteine und ein paar JavaScript Funktionen in die Hand; du musst die fehlenden JavaScript-Teile ergänzen, um alles zu einem lauffähigen Programm zu kombinieren, was Folgendes tun kann:

+ + + +

Der folgende Screenshot zeigt dir ein Beispiel, wie die Ausgabe deines geschriebenen Programmes aussehen wird:

+ +

+ +

Um dich noch mehr mit deiner Arbeit vertraut zu machen, schau dir die fertige Lösung an (ohne im Quellcode zu spicken! )

+ +

Schritt-für-Schritt Anleitung

+ +

In den folgenden Abschnitten wird dir erklärt, was du tun musst.

+ +

Grundaufbau:

+ +
    +
  1. Erzeuge eine Datei mit dem Namen main.js, und zwar im selben Verzeichnis, wie deine index.html Datei.
  2. +
  3. Verbinde deine externe JavaScript Datei main.js mit deiner HTML Datei, indem du es mithilfe des Script-tags {{htmlelement("script")}} in deinem HTML aufrufst. Füge die Zeile kurz vor dem schließenden </body> tag ein.
  4. +
+ +

 Vorgegebene Variablen und Functions:

+ +
    +
  1. Kopiere alle Code-Zeilen aus der Roh-Text-Datei, die unter der Überschrift "1. COMPLETE VARIABLE AND FUNCTION DEFINITIONS" stehen und füge Sie an den Anfang deiner main.js Datei. Im Code wirst du 3 Variablen entdecken, die sich auf verschiedene Teile der Ausgabe beziehen: (customName) bezieht sich auf das "Enter custom name" Text Feld , the "Generate random story" button (randomize), and the {{htmlelement("p")}} element at the bottom of the HTML body that the story will be copied into (story), respectively. In addition you've got a function called randomValueFromArray() that takes an array, and returns one of the items stored inside the array at random.
  2. +
  3. Now look at the second section of the raw text file — "2. RAW TEXT STRINGS". This contains text strings that will act as input into our program. We'd like you to contain these inside variables inside main.js: +
      +
    1. Store the first, big long, string of text inside a variable called storyText.
    2. +
    3. Store the first set of three strings inside an array called insertX.
    4. +
    5. Store the second set of three strings inside an array called insertY.
    6. +
    7. Store the third set of three strings inside an array called insertZ.
    8. +
    +
  4. +
+ +

Placing the event handler and incomplete function:

+ +
    +
  1. Now return to the raw text file.
  2. +
  3. Copy the code found underneath the heading "3. EVENT LISTENER AND PARTIAL FUNCTION DEFINITION" and paste it into the bottom of your main.js file. This: +
      +
    • Adds a click event listener to the randomize variable so that when the button it represents is clicked, the result() function is run.
    • +
    • Adds a partially-completed result() function definiton to your code. For the remainder of the assessment, you'll be filling in lines inside this function to complete it and make it work properly.
    • +
    +
  4. +
+ +

Completing the result() function:

+ +
    +
  1. Create a new variable called newStory, and set it's value to equal storyText. This is needed so we can create a new random story each time the button is pressed and the function is run. If we made changes directly to storyText, we'd only be able to generate a new story once.
  2. +
  3. Create three new variables called xItem, yItem, and zItem, and make them equal to the result of calling randomValueFromArray() on your three arrays (the result in each case will be a random item out of each array it is called on). For example you can call the function and get it to return one random string out of insertX by writing randomValueFromArray(insertX).
  4. +
  5. Next we want to replace the three placeholders in the newStory string — :insertx:, :inserty:, and :insertz: — with the strings stored in xItem, yItem, and zItem. There is a particular string method that will help you here — in each case, make the call to the method equal to newStory, so each time it is called, newStory is made equal to itself, but with substitutions made. So each time the button is pressed, these placeholders are each replaced with a random silly string. As a further hint, the method in question only replaces the first instance of the substring it finds, so you might need to make one of the calls twice.
  6. +
  7. Inside the first if block, add another string replacement method call to replace the name 'Bob' found in the newStory string with the name variable. In this block we are saying "If a value has been entered into the customName text input, replace Bob in the story with that custom name."
  8. +
  9. Inside the second if block, we are checking to see if the uk radio button has been selected. If so, we want to convert the weight and temperature values in the story from pounds and Fahrenheit into stones and centigrade. What you need to do is as follows: +
      +
    1. Look up the formulae for converting pounds to stone, and Fahrenheit to centigrade.
    2. +
    3. Inside the line that defines the weight variable, replace 300 with a calculation that converts 300 pounds into stones. Concatenate ' stone' onto the end of the result of the overall Math.round() call.
    4. +
    5. Inside the line that defines the temperature variable, replace 94 with a calculation that converts 94 Fahrenheit into centigrade. Concatenate ' centigrade' onto the end of the result of the overall Math.round() call.
    6. +
    7. Just under the two variable definitions, add two more string replacement lines that replace '94 fahrenheit' with the contents of the temperature variable, and '300 pounds' with the contents of the weight variable.
    8. +
    +
  10. +
  11. Finally, in the second-to-last line of the function, make the textContent property of the story variable (which references the paragraph) equal to newStory.
  12. +
+ +

Hints and tips

+ + + +

Assessment

+ +

If you are following this assessment as part of an organized course, you should be able to give your work to your teacher/mentor for marking. If you are self-learning, then you can get the marking guide fairly easily by asking on the discussion thread for this exercise, or in the #mdn IRC channel on Mozilla IRC. Try the exercise first — there is nothing to be gained by cheating!

+ +

{{PreviousMenu("Learn/JavaScript/First_steps/Arrays", "Learn/JavaScript/First_steps")}}

+ +

In this module

+ + diff --git a/files/de/learn/javascript/first_steps/useful_string_methods/index.html b/files/de/learn/javascript/first_steps/useful_string_methods/index.html new file mode 100644 index 0000000000..e0df907ade --- /dev/null +++ b/files/de/learn/javascript/first_steps/useful_string_methods/index.html @@ -0,0 +1,656 @@ +--- +title: Useful string methods +slug: Learn/JavaScript/First_steps/Useful_string_methods +translation_of: Learn/JavaScript/First_steps/Useful_string_methods +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/First_steps/Strings", "Learn/JavaScript/First_steps/Arrays", "Learn/JavaScript/First_steps")}}
+ +

Jetzt, da wir die Basics kennengelernt haben, gehen wir einen Schritt weiter und sehen uns hilfreiche Methoden an, die wir im Umgang mit Strings anwenden können. Dazu zählt zum Beispiel die Länge eines Textes, hinzufügen oder splitten von Strings, das Austauschen eines Buchstaben in einem Text-String und mehr...

+ + + + + + + + + + + + +
Voraussetzungen:Grundlegende Computerkenntnisse, ein grundlegendes Verständnis von HTML und CSS, ein Verständnis dafür, was JavaScript ist.
Ziel:Zu verstehen, dass Zeichenketten Objekte sind, und zu lernen, wie man einige der grundlegenden Methoden, die auf diesen Objekten verfügbar sind, verwendet, um Zeichenketten zu manipulieren.
+ +

Zeichenketten als Objekte

+ +

Die meisten Dinge in JavaScript sind Objekte. Wenn Sie einen String erstellen, zum Beispiel durch die Verwendung von

+ +
let string = 'This is my string';
+ +

wird Ihre Variable zu einer String-Objektinstanz und hat als Ergebnis eine große Anzahl von Eigenschaften und Methoden zur Verfügung. Sie können dies sehen, wenn Sie auf die {{jsxref("String")}} Objektseite gehen und die Liste auf der Seite nach unten scrollen!

+ +

Sooo, bevor Du jetzt Kopfschmerzen bekommst: Die meisten der Methoden must du jetzt am Anfang noch nicht wirklich kennen. Allerdings gibt es da ein paar, die Du am Anfang und später ziemlich oft nutzen wirst. Werfen wir also einen Blick darauf:

+ +

Starten wir mit ein paar Beispielen in der browser developer console.

+ +

Länge einer Zeichenkette

+ +

Das ist einfach. Nutze einfach {{jsxref("String.prototype.length", "length")}} . Probiere einfach mal folgenden Code:

+ +
let browserType = 'mozilla';
+browserType.length;
+ +

Das sollte Dir eine "7" zurückgeben, denn "mozilla" ist 7 Zeichen lang. Das kann man für verschiedene Dinge nutzen; Zum Beispiel: Du möchtest die Zeichenlänge einer Reihe von Namen herausfinden, um diese in der Reihenfolge ihrer Länge auszugeben. Oder lasse einen Nutzer wissen, das seine gerade getätigte Eingabe des Usernamens viel zu lang ist und nicht den Vorgaben entspricht.

+ +

Retrieving a specific string character

+ +

On a related note, you can return any character inside a string by using square bracket notation — this means you include square brackets ([]) on the end of your variable name. Inside the square brackets you include the number of the character you want to return, so for example to retrieve the first letter you'd do this:

+ +
browserType[0];
+ +

Remember: computers count from 0, not 1! You could use this to, for example, find the first letter of a series of strings and order them alphabetically.

+ +

To retrieve the last character of any string, we could use the following line, combining this technique with the length property we looked at above:

+ +
browserType[browserType.length-1];
+ +

The length of "mozilla" is 7, but because the count starts at 0, the character position is 6; using  length-1 gets us the last character.

+ +

Finding a substring inside a string and extracting it

+ +
    +
  1. Sometimes you'll want to find if a smaller string is present inside a larger one (we generally say if a substring is present inside a string). This can be done using the {{jsxref("String.prototype.indexOf()", "indexOf()")}} method, which takes a single {{glossary("parameter")}} — the substring you want to search for. Try this: + +
    browserType.indexOf('zilla');
    + This gives us a result of 2, because the substring "zilla" starts at position 2 (0, 1, 2  — so 3 characters in) inside "mozilla". Such code could be used to filter strings. For example, we may have a list of web addresses and only want to print out the ones that contain "mozilla".
  2. +
+ +
    +
  1. This can be done in another way, which is possibly even more effective. Try the following: +
    browserType.indexOf('vanilla');
    + This should give you a result of -1 — this is returned when the substring, in this case 'vanilla', is not found in the main string.
    +
    + You could use this to find all instances of strings that don't contain the substring 'mozilla', or do, if you use the negation operator, as shown below. You could do something like this: + +
    if(browserType.indexOf('mozilla') !== -1) {
    +  // do stuff with the string
    +}
    +
  2. +
  3. When you know where a substring starts inside a string, and you know at which character you want it to end, {{jsxref("String.prototype.slice()", "slice()")}} can be used to extract it. Try the following: +
    browserType.slice(0,3);
    + This returns "moz" — the first parameter is the character position to start extracting at, and the second parameter is the character position after the last one to be extracted. So the slice happens from the first position, up to, but not including, the last position. In this example, since the starting index is 0, the second parameter is equal to the length of the string being returned.
    +  
  4. +
  5. Also, if you know that you want to extract all of the remaining characters in a string after a certain character, you don't have to include the second parameter! Instead, you only need to include the character position from where you want to extract the remaining characters in a string. Try the following: +
    browserType.slice(2);
    + This returns "zilla" — this is because the character position of 2 is the letter z, and because you didn't include a second parameter, the substring that was returned was all of the remaining characters in the string. 
  6. +
+ +
+

Note: The second parameter of slice() is optional: if you don't include it, the slice ends at the end of the original string. There are other options too; study the {{jsxref("String.prototype.slice()", "slice()")}} page to see what else you can find out.

+
+ +

Changing case

+ +

The string methods {{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}} and {{jsxref("String.prototype.toUpperCase()", "toUpperCase()")}} take a string and convert all the characters to lower- or uppercase, respectively. This can be useful for example if you want to normalize all user-entered data before storing it in a database.

+ +

Let's try entering the following lines to see what happens:

+ +
let radData = 'My NaMe Is MuD';
+radData.toLowerCase();
+radData.toUpperCase();
+ +

Updating parts of a string

+ +

You can replace one substring inside a string with another substring using the {{jsxref("String.prototype.replace()", "replace()")}} method. This works very simply at a basic level, although there are some advanced things you can do with it that we won't go into yet.

+ +

It takes two parameters — the string you want to replace, and the string you want to replace it with. Try this example:

+ +
browserType.replace('moz','van');
+ +

This returns "vanilla" in the console. But if you check the value of browserType, it is still "mozilla'. To actually update the value of the browserType variable in a real program, you'd have to set the variable value to be the result of the operation; it doesn't just update the substring value automatically. So you'd have to actually write this: browserType = browserType.replace('moz','van');

+ +

Active learning examples

+ +

In this section we'll get you to try your hand at writing some string manipulation code. In each exercise below, we have an array of strings, and a loop that processes each value in the array and displays it in a bulleted list. You don't need to understand arrays or loops right now — these will be explained in future articles. All you need to do in each case is write the code that will output the strings in the format that we want them in.

+ +

Each example comes with a "Reset" button, which you can use to reset the code if you make a mistake and can't get it working again, and a "Show solution" button you can press to see a potential answer if you get really stuck.

+ +

Filtering greeting messages

+ +

In the first exercise we'll start you off simple — we have an array of greeting card messages, but we want to sort them to list just the Christmas messages. We want you to fill in a conditional test inside the if( ... ) structure, to test each string and only print it in the list if it is a Christmas message.

+ +
    +
  1. First think about how you could test whether the message in each case is a Christmas message. What string is present in all of those messages, and what method could you use to test whether it is present?
  2. +
  3. You'll then need to write a conditional test of the form operand1 operator operand2. Is the thing on the left equal to the thing on the right? Or in this case, does the method call on the left return the result on the right?
  4. +
  5. Hint: In this case it is probably more useful to test whether the method call isn't equal to a certain result.
  6. +
+ + + +

{{ EmbedLiveSample('Playable_code', '100%', 590, "", "", "hide-codepen-jsfiddle") }}

+ +

Fixing capitalization

+ +

In this exercise we have the names of cities in the United Kingdom, but the capitalization is all messed up. We want you to change them so that they are all lower case, except for a capital first letter. A good way to do this is to:

+ +
    +
  1. Convert the whole of the string contained in the input variable to lower case and store it in a new variable.
  2. +
  3. Grab the first letter of the string in this new variable and store it in another variable.
  4. +
  5. Using this latest variable as a substring, replace the first letter of the lowercase string with the first letter of the lowercase string changed to upper case. Store the result of this replace procedure in another new variable.
  6. +
  7. Change the value of the result variable to equal to the final result, not the input.
  8. +
+ +
+

Note: A hint — the parameters of the string methods don't have to be string literals; they can also be variables, or even variables with a method being invoked on them.

+
+ + + +

{{ EmbedLiveSample('Playable_code_2', '100%', 550, "", "", "hide-codepen-jsfiddle") }}

+ +

Making new strings from old parts

+ +

In this last exercise, the array contains a bunch of strings containing information about train stations in the North of England. The strings are data items that contain the three-letter station code, followed by some machine-readable data, followed by a semicolon, followed by the human-readable station name. For example:

+ +
MAN675847583748sjt567654;Manchester Piccadilly
+ +

We want to extract the station code and name, and put them together in a string with the following structure:

+ +
MAN: Manchester Piccadilly
+ +

We'd recommend doing it like this:

+ +
    +
  1. Extract the three-letter station code and store it in a new variable.
  2. +
  3. Find the character index number of the semicolon.
  4. +
  5. Extract the human-readable station name using the semicolon character index number as a reference point, and store it in a new variable.
  6. +
  7. Concatenate the two new variables and a string literal to make the final string.
  8. +
  9. Change the value of the result variable to equal to the final string, not the input.
  10. +
+ + + +

{{ EmbedLiveSample('Playable_code_3', '100%', 585, "", "", "hide-codepen-jsfiddle") }}

+ +

Conclusion

+ +

You can't escape the fact that being able to handle words and sentences in programming is very important — particularly in JavaScript, as websites are all about communicating with people. This article has given you the basics that you need to know about manipulating strings for now. This should serve you well as you go into more complex topics in the future. Next, we're going to look at the last major type of data we need to focus on in the short term — arrays.

+ +

{{PreviousMenuNext("Learn/JavaScript/First_steps/Strings", "Learn/JavaScript/First_steps/Arrays", "Learn/JavaScript/First_steps")}}

+ +

In this module

+ + diff --git a/files/de/learn/javascript/first_steps/variables/index.html b/files/de/learn/javascript/first_steps/variables/index.html new file mode 100644 index 0000000000..d8906f7d02 --- /dev/null +++ b/files/de/learn/javascript/first_steps/variables/index.html @@ -0,0 +1,386 @@ +--- +title: Speichern der benötigten Informationen — Variablen +slug: Learn/JavaScript/First_steps/Variables +translation_of: Learn/JavaScript/First_steps/Variables +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/First_steps/What_went_wrong", "Learn/JavaScript/First_steps/Math", "Learn/JavaScript/First_steps")}}
+ +

After reading the last couple of articles you should now know what JavaScript is, what it can do for you, how you use it alongside other web technologies, and what its main features look like from a high level. In this article, we will get down to the real basics, looking at how to work with the most basic building blocks of JavaScript — Variables.

+ + + + + + + + + + + + +
Prerequisites:Basic computer literacy, a basic understanding of HTML and CSS, an understanding of what JavaScript is.
Objective:To gain familiarity with the basics of JavaScript variables.
+ +

Tools you need

+ +

Throughout this article, you'll be asked to type in lines of code to test your understanding of the content. If you are using a desktop browser, the best place to type your sample code is your browser's JavaScript console (see What are browser developer tools for more information on how to access this tool).

+ +

However, we have also provided a simple JavaScript console embedded in the page below for you to enter this code into, in case you are not using a browser with a JavaScript console easily available, or find an in-page console more comfortable.

+ +

Was ist eine Variable?

+ +

Eine Variable ist ein Behälter für einen Wert, wie z.B. eine Zahl, welche wir vielleicht für eine Summe benötigen, oder eine Zeichenkette die wir für einen Teil eines Satzes brauchen. Eine Besonderheit von Variablen ist, dass ihr Wert verändert werden kann. Hier ein Beispiel:

+ +
<button>Press me</button>
+ +
var button = document.querySelector('button');
+
+button.onclick = function() {
+  var name = prompt('Wie heißt du?');
+  alert('Hallo ' + name + ', schön dich zu sehen!');
+}
+ +

{{ EmbedLiveSample('What_is_a_variable', '100%', 50, "", "", "hide-codepen-jsfiddle") }}

+ +

In diesem Beispiel werden beim Drücken des Buttons einige Zeilen Code ausgeführt. Die erste Zeile zeigt eine Box an, welche den Leser nach seinem Namen fragt und den Wert anschließend in einer Variable abspeichert. Die zweite Zeile zeigt eine Willkommensnachricht, die den Namen enthält, welcher dem Wert der Variable entnommen wird.

+ +

Um zu verstehen, warum das so nützlich ist, überlegen wir mal, wie wir das Beispiel ohne eine Variable schreiben würden. Es würde etwa so aussehen:

+ +
var name = prompt('Wie heißt du?');
+
+if (name === 'Adam') {
+  alert('Hallo Adam, schön dich zu sehen!');
+} else if (name === 'Alan') {
+  alert('Hallo Alan, schön dich zu sehen!');
+} else if (name === 'Bella') {
+  alert('Hallo Bella, schön dich zu sehen!');
+} else if (name === 'Bianca') {
+  alert('Hallo Bianca, schön dich zu sehen!');
+} else if (name === 'Chris') {
+  alert('Hallo Chris, schön dich zu sehen!');
+}
+
+// ... und so weiter ...
+ +

You may not fully understand the syntax we are using (yet!), but you should be able to get the idea — if we didn't have variables available, we'd have to implement a giant code block that checked what the entered name was, and then display the appropriate message for that name. This is obviously really inefficient (the code is a lot bigger, even for only five choices), and it just wouldn't work — you couldn't possibly store all possible choices.

+ +

Variables just make sense, and as you learn more about JavaScript they will start to become second nature.

+ +

Another special thing about variables is that they can contain just about anything — not just strings and numbers. Variables can also contain complex data and even entire functions to do amazing things. You'll learn more about this as you go along.

+ +

Note that we say variables contain values. This is an important distinction to make. Variables aren't the values themselves; they are containers for values. You can think of them being like little cardboard boxes that you can store things in.

+ +

+ +

Eine Variable deklarieren

+ +

To use a variable you've first got to create it — more accurately, we call this declaring the variable. To do this, we type the keyword var followed by the name you want to call your variable:

+ +
var myName;
+var myAge;
+ +

Here we're creating two variables called myName and myAge. Try typing these lines in now in your web browser's console, or in the below console (You can open this console in a separate tab or window if you'd prefer that). After that, try creating a variable (or two) with your own name choices.

+ + + +

{{ EmbedLiveSample('Hidden_code', '100%', 300, "", "", "hide-codepen-jsfiddle") }}

+ +
+

Note: In JavaScript, all code instructions should end with a semi-colon (;) — your code may work correctly for single lines, but probably won't when you are writing multiple lines of code together. Try to get into the habit of including it.

+
+ +

You can test whether these values now exist in the execution environment by typing just the variable's name, e.g.

+ +
myName;
+myAge;
+ +

They currently have no value; they are empty containers. When you enter the variable names, you should get a value of undefined returned. If they don't exist, you'll get an error message — try typing in

+ +
scoobyDoo;
+ +
+

Note: Don't confuse a variable that exists but has no value defined with a variable that doesn't exist at all — they are very different things. In the box analogy you saw above, not existing would mean there's no box (variable) for a value to go in. No value defined would mean that there IS a box, but it has no value inside it.

+
+ +

Eine Variable initialisieren

+ +

Once you've declared a variable, you can initialize it with a value. You do this by typing the variable name, followed by an equals sign (=), followed by the value you want to give it. For example:

+ +
myName = 'Chris';
+myAge = 37;
+ +

Try going back to the console now and typing in these lines. You should see the value you've assigned to the variable returned in the console to confirm it, in each case. Again, you can return your variable values by simply typing their name into the console — try these again:

+ +
myName;
+myAge;
+ +

You can declare and initialize a variable at the same time, like this:

+ +
var myName = 'Chris';
+ +

This is probably what you'll do most of the time, as it is quicker than doing the two actions on two separate lines.

+ +
+

Note: If you write a multiline JavaScript program that declares and initializes a variable, you can actually declare it after you initialize it and it will still work. This is because variable declarations are generally done first before the rest of the code is executed. This is called hoisting — read var hoisting for more detail on the subject.

+
+ +

Eine Variable aktualisieren

+ +

Once a variable has been initialized with a value, you can change (or update) that value by simply giving it a different value. Try entering the following lines into your console:

+ +
myName = 'Bob';
+myAge = 40;
+ +

An aside on variable naming rules

+ +

You can call a variable pretty much anything you like, but there are limitations. Generally, you should stick to just using Latin characters (0-9, a-z, A-Z) and the underscore character.

+ + + +
+

Note: You can find a fairly complete list of reserved keywords to avoid at Lexical grammar — keywords.

+
+ +

Good name examples:

+ +
age
+myAge
+init
+initialColor
+finalOutputValue
+audio1
+audio2
+ +

Bad name examples:

+ +
1
+a
+_12
+myage
+MYAGE
+var
+Document
+skjfndskjfnbdskjfb
+thisisareallylongstupidvariablenameman
+ +

Error-prone name examples:

+ +
var
+Document
+
+ +

Try creating a few more variables now, with the above guidance in mind.

+ +

Typen von Variablen

+ +

There are a few different types of data we can store in variables. In this section we'll describe these in brief, then in future articles, you'll learn about them in more detail.

+ +

So far we've looked at the first two, but there are others.

+ +

Numbers

+ +

You can store numbers in variables, either whole numbers like 30 (also called integers) or decimal numbers like 2.456 (also called floats or floating point numbers). You don't need to declare variable types in JavaScript, unlike some other programming languages. When you give a variable a number value, you don't include quotes:

+ +
var myAge = 17;
+ +

Strings

+ +

Strings are pieces of text. When you give a variable a string value, you need to wrap it in single or double quote marks, otherwise, JavaScript will try to interpret it as another variable name.

+ +
var dolphinGoodbye = 'So long and thanks for all the fish';
+ +

Booleans

+ +

Booleans are true/false values — they can have two values, true or false. These are generally used to test a condition, after which code is run as appropriate. So for example, a simple case would be:

+ +
var iAmAlive = true;
+ +

Whereas in reality it would be used more like this:

+ +
var test = 6 < 3;
+ +

This is using the "less than" operator (<) to test whether 6 is less than 3. As you might expect, it will return false, because 6 is not less than 3! You will learn a lot more about such operators later on in the course.

+ +

Arrays

+ +

An array is a single object that contains multiple values enclosed in square brackets and separated by commas. Try entering the following lines into your console:

+ +
var myNameArray = ['Chris', 'Bob', 'Jim'];
+var myNumberArray = [10,15,40];
+ +

Once these arrays are defined, you can access each value by their location within the array. Try these lines:

+ +
myNameArray[0]; // should return 'Chris'
+myNumberArray[2]; // should return 40
+ +

The square brackets specify an index value corresponding to the position of the value you want returned. You might have noticed that arrays in JavaScript are zero-indexed: the first element is at index 0.

+ +

You'll learn a lot more about arrays in a future article.

+ +

Objects

+ +

In programming, an object is a structure of the code that models a real-life object. You can have a simple object that represents a car park and contains information about its width and length, or you could have an object that represents a person, and contains data about their name, height, weight, what language they speak, how to say hello to them, and more.

+ +

Try entering the following line into your console:

+ +
var dog = { name : 'Spot', breed : 'Dalmatian' };
+ +

To retrieve the information stored in the object, you can use the following syntax:

+ +
dog.name
+ +

We won't be looking at objects any more for now — you can learn more about those in a future module.

+ +

Dynamic typing

+ +

JavaScript is a "dynamically typed language", which means that, unlike some other languages, you don't need to specify what data type a variable will contain (e.g. numbers, strings, arrays, etc).

+ +

For example, if you declare a variable and give it a value encapsulated in quotes, the browser will treat the variable as a string:

+ +
var myString = 'Hello';
+ +

It will still be a string, even if it contains numbers, so be careful:

+ +
var myNumber = '500'; // oops, this is still a string
+typeof myNumber;
+myNumber = 500; // much better — now this is a number
+typeof myNumber;
+ +

Try entering the four lines above into your console one by one, and see what the results are. You'll notice that we are using a special operator called typeof — this returns the data type of the variable you pass into it. The first time it is called, it should return string, as at that point the myNumber variable contains a string, '500'. Have a look and see what it returns the second time you call it.

+ +

Zusammenfassung

+ +

By now you should know a reasonable amount about JavaScript variables and how to create them. In the next article, we'll focus on numbers in more detail, looking at how to do basic math in JavaScript.

+ +

{{PreviousMenuNext("Learn/JavaScript/First_steps/What_went_wrong", "Learn/JavaScript/First_steps/Maths", "Learn/JavaScript/First_steps")}}

+ +

In this module

+ + diff --git a/files/de/learn/javascript/first_steps/was_ist_javascript/index.html b/files/de/learn/javascript/first_steps/was_ist_javascript/index.html new file mode 100644 index 0000000000..247b4744c5 --- /dev/null +++ b/files/de/learn/javascript/first_steps/was_ist_javascript/index.html @@ -0,0 +1,339 @@ +--- +title: Was ist JavaScript? +slug: Learn/JavaScript/First_steps/Was_ist_JavaScript +translation_of: Learn/JavaScript/First_steps/What_is_JavaScript +--- +
{{LearnSidebar}}
+ +
{{NextMenu("Learn/JavaScript/First_steps/A_first_splash", "Learn/JavaScript/First_steps")}}
+ +

Willkommen zum MDN-Einsteigerkurs für JavaScript! Im ersten Artikel werden wir uns JavaScript von aussen anschauen und Fragen beantworten wie "Was ist das?" oder  "Was macht das?", und wir stellen sicher, das du weißt was JavaScript ist.

+ + + + + + + + + + + + +
Voraussetzungen:Umgang mit einem Computer und ein Grundverständniss von HTML und CSS
Thema:JavaScript kennenlernen, was JavaScript tun kann und wie es in einer Webseite arbeitet.
+ +

Eine Experten Definition

+ +

JavaScript ist eine Programmiersprache mit der sich komplexe Programme in eine Webseite realisieren lassen. Immer wenn eine Webseite mehr macht als nur statische Informationen anzuzeigen, (zum Beispiel:

+ + + +

kannst du dir sicher sein das JavaScript benutzt wurde. Es ist die Dritte der Drei Standard-Technologien im Web, die anderen beiden ( HTML und CSS ) werden in anderen Bereichen des MDN eingeführt und referenziert.

+ +

+ + + +

Die drei Teile bauen gut auf einander auf. Hier mal ein einfaches Beispiel: Wir können zunächst HTML benutzten, um eine Struktur zu bauen.

+ +
<p>Player 1: Chris</p>
+ +

+ +

Anschließend können wir mit einigen CSS-Regeln denn Satz schön aussehen lassen:

+ +
p {
+  font-family: 'helvetica neue', helvetica, sans-serif;
+  letter-spacing: 1px;
+  text-transform: uppercase;
+  text-align: center;
+  border: 2px solid rgba(0,0,200,0.6);
+  background: rgba(0,0,200,0.3);
+  color: rgba(0,0,200,0.6);
+  box-shadow: 1px 1px 2px rgba(0,0,200,0.4);
+  border-radius: 10px;
+  padding: 3px 10px;
+  display: inline-block;
+  cursor:pointer;
+}
+ +

+ +

Und zum Schluss können wir mit etwas JavaScript eine Reaktion auf das Klicken des Benutzers implementieren:

+ +
var para = document.querySelector('p');
+
+para.addEventListener('click', updateName);
+
+function updateName() {
+  var name = prompt('Enter a new name');
+  para.textContent = 'Player 1: ' + name;
+}
+
+ +

{{ EmbedLiveSample('A_high-level_definition', '100%', 80) }}

+ +

Klick auf das Label und sieh, was passiert (den Code findest du auf GitHub und hier kannst du es in Aktion sehen).

+ +

So und was kann ich jetzt damit machen?

+ +

Der Kern von JavaScript ähnelt dem anderer Programmiersprachen. In JavaScript kannst du:

+ + + +

Aber es gibt noch andere Funktionen die auf dem Kern von JavaScript aufbauen. Die sogenannten Application Programming Interfaces (APIs) geben dir noch mehr Funktionen mit denen du deine Projekte aufbessern kann.

+ +

APIs sind von anderen Programmieren geschriebener Code die dir mehr Möglichkeiten geben für dein Programm. Die für dich schwer oder unmöglich wären selber zu programmieren. Sie sind das gleiche was Werkzeuge und Material für Handwerker sind. Es wäre deutlich schwerer alleine erst alle Werkzeuge und dann alle Materiallien herzustellen.

+ +

Die APIs kann man generell in zwei Kategorien einteilen:

+ +

+ +

Browser APIs sind vom Webbrowser des Benutzers. Und sie können auf Ressourcen des computers zugreifen, oder erledigen Dinge die sehr komlpex sind. Ein paar Beispiele:

+ + + +
+

Notiz: Viele der oben genannten Beispiele funktionieren in älteren Browsern nicht — wenn du dein Code ausprobieren willst, dann ist es eine gute Idee einen Modernen Browser wie Firefox, Chrome, Edge oder Opera zu benutzen. Es wird trotzdem nötig sein, sich mit Cross Browser Testing auseinander zu setzen, wenn es näher an eine Produktionssystem gehen soll(z.B. Echter Code die echte Kunden benutzen sollen).

+
+ +

Drittanbieter-APIssind nicht standardmäßig im Browser integriert, und du wirst großenteils deren Code und Informationen von wo anders finden müssen. Zum Beispiel

+ + + +
+

Notiz: Diese APIs sind sehr fortschrittlich und werden in diesem Modul nicht weiter behandelt.Du findest weitere Informationen bei unseren ModulClientbasierte Web APIs Modul.

+
+ +

Es sind noch viele weitere APIs Verfügbar! Trotzdem werde jetzt nicht zu aufgeregt, denn du wirst es nicht schaffen, das nächste Facebook, Google Maps, oder Instagram zu entwickeln, nach gerade mal 24 Stunden JavaScript lernen — es gibt nämlich noch viele Sachen die Behandelt werden müssen. Und deswegen bist du hier — also lass uns weiter machen!

+ +

Was genau macht JavaScript auf deiner Webseite?

+ +

Here we'll start actually looking at some code, and while doing so explore what actually happens when you run some JavaScript in your page.

+ +

Let's briefly recap the story of what happens when you load a web page in a browser (first talked about in our How CSS works article). When you load a web page in your browser, you are running your code (the HTML, CSS, and JavaScript) inside an execution environment (the browser tab). This is like a factory that takes in raw materials (the code) and outputs a product (the web page).

+ +

+ +

The JavaScript is executed by the browser's JavaScript engine, after the HTML and CSS have been assembled and put together into a web page. This ensures that the structure and style of the page are already in place by the time the JavaScript starts to run.

+ +

This is a good thing, as a very common use of JavaScript is to dynamically modify HTML and CSS to update a user interface, via the Document Object Model API (as mentioned above). If the JavaScript loaded and tried to run before the HTML and CSS was there to affect, then errors would occur.

+ +

Browser Sicherheit

+ +

Each browser tab is its own separate bucket for running code in (these buckets are called "execution environments" in technical terms) — this means that in most cases the code in each tab is run completely separately, and the code in one tab cannot directly affect the code in another tab — or on another website. This is a good security measure — if this were not the case, then pirates could start writing code to steal information from other websites, and other such bad things.

+ +
+

Note: There are ways to send code and data between different websites/tabs in a safe manner, but these are advanced techniques that we won't cover in this course.

+
+ +

JavaScript running order

+ +

When the browser encounters a block of JavaScript, it generally runs it in order, from top to bottom. This means that you need to be careful what order you put things in. For example, let's return to the block of JavaScript we saw in our first example:

+ +
var para = document.querySelector('p');
+
+para.addEventListener('click', updateName);
+
+function updateName() {
+  var name = prompt('Enter a new name');
+  para.textContent = 'Player 1: ' + name;
+}
+ +

Here we are selecting a text paragraph (line 1), then attaching an event listener to it (line 3) so that when the paragraph is clicked, the updateName() code block (lines 5–8) is run. The updateName() code block (these types of reusable code block are called "functions") asks the user for a new name, and then inserts that name into the paragraph to update the display.

+ +

If you swapped the order of the first two lines of code, it would no longer work — instead, you'd get an error returned in the browser developer console — TypeError: para is undefined. This means that the para object does not exist yet, so we can't add an event listener to it.

+ +
+

Note: This is a very common error — you need to be careful that the objects referenced in your code exist before you try to do stuff to them.

+
+ +

Interpreted versus compiled code

+ +

You might hear the terms interpreted and compiled in the context of programming. JavaScript is an interpreted language — the code is run from top to bottom and the result of running the code is immediately returned. You don't have to transform the code into a different form before the browser runs it.

+ +

Compiled languages on the other hand are transformed (compiled) into another form before they are run by the computer. For example C/C++ are compiled into assembly language that is then run by the computer.

+ +

Both approaches have different advantages, which we won't discuss at this point.

+ +

Server-side versus client-side code

+ +

You might also hear the terms server-side and client-side code, specially in the context of web development. Client-side code is code that is run on the user's computer — when a web page is viewed, the page's client-side code is downloaded, then run and displayed by the browser. In this JavaScript module we are explicitly talking about client-side JavaScript.

+ +

Server-side code on the other hand is run on the server, then its results are downloaded and displayed in the browser. Examples of popular server-side web languages include PHP, Python, Ruby, and ASP.NET. And JavaScript! JavaScript can also be used as a server-side language, for example in the popular Node.js environment — you can find more out about server-side JavaScript in our Dynamic Websites – Server-side programming topic.

+ +

The word dynamic is used to describe both client-side JavaScript, and server-side languages — it refers to the ability to update the display of a web page/app to show different things in different circumstances, generating new content as required. Server-side code dynamically generates new content on the server, e.g. pulling data from a database, whereas client-side JavaScript dynamically generates new content inside the browser on the client, e.g. creating a new HTML table, inserting data requested from the server into it, then displaying the table in a web page shown to the user. The meaning is slightly different in the two contexts, but related, and both approaches (server-side and client-side) usually work together.

+ +

A web page with no dynamically updating content is referred to as static — it just shows the same content all the time.

+ +

How do you add JavaScript to your page?

+ +

JavaScript is applied to your HTML page in a similar manner to CSS. Whereas CSS uses {{htmlelement("link")}} elements to apply external stylesheets and {{htmlelement("style")}} elements to apply internal stylesheets to HTML, JavaScript only needs one friend in the world of HTML — the {{htmlelement("script")}} element. Let's learn how this works.

+ +

Internal JavaScript

+ +
    +
  1. First of all, make a local copy of our example file apply-javascript.html. Save it in a directory somewhere sensible.
  2. +
  3. Open the file in your web browser and in your text editor. You'll see that the HTML creates a simple web page containing a clickable button.
  4. +
  5. Next, go to your text editor and add the following just before your closing </body> tag: +
    <script>
    +
    +  // JavaScript goes here
    +
    +</script>
    +
  6. +
  7. Now we'll add some JavaScript inside our {{htmlelement("script")}} element to make the page do something more interesting — add the following code just below the "// JavaScript goes here" line: +
    function createParagraph() {
    +  var para = document.createElement('p');
    +  para.textContent = 'You clicked the button!';
    +  document.body.appendChild(para);
    +}
    +
    +var buttons = document.querySelectorAll('button');
    +
    +for (var i = 0; i < buttons.length ; i++) {
    +  buttons[i].addEventListener('click', createParagraph);
    +}
    +
  8. +
  9. Save your file and refresh the browser — now you should see that when you click the button, a new paragraph is generated and placed below.
  10. +
+ +
+

Note: If your example doesn't seem to work, go through the steps again and check that you did everything right. Did you save your local copy of the starting code as a .html file? Did you add your {{htmlelement("script")}} element just before the </body> tag? Did you enter the JavaScript exactly as shown? JavaScript is case sensitive, and very fussy, so you need to enter the syntax exactly as shown, otherwise it may not work.

+
+ +
+

Note: You can see this version on GitHub as apply-javascript-internal.html (see it live too).

+
+ +

External JavaScript

+ +

This works great, but what if we wanted to put our JavaScript in an external file? Let's explore this now.

+ +
    +
  1. First, create a new file in the same directory as your sample HTML file. Call it script.js — make sure it has that .js filename extension, as that's how it is recognized as JavaScript.
  2. +
  3. Next, copy all of the script out of your current {{htmlelement("script")}} element and paste it into the .js file. Save that file.
  4. +
  5. Now replace your current {{htmlelement("script")}} element with the following: +
    <script src="script.js"></script>
    +
  6. +
  7. Save and refresh your browser, and you should see the same thing! It works just the same, but now we've got the JavaScript in an external file. This is generally a good thing in terms of organizing your code, and making it reusable across multiple HTML files. Plus the HTML is easier to read without huge chunks of script dumped in it.
  8. +
+ +

Note: You can see this version on GitHub as apply-javascript-external.html and script.js (see it live too).

+ +

Inline JavaScript handlers

+ +

Note that sometimes you'll come across bits of actual JavaScript code living inside HTML. It might look something like this:

+ +
function createParagraph() {
+  var para = document.createElement('p');
+  para.textContent = 'You clicked the button!';
+  document.body.appendChild(para);
+}
+ +
<button onclick="createParagraph()">Click me!</button>
+ +

You can try this version of our demo below.

+ +

{{ EmbedLiveSample('Inline_JavaScript_handlers', '100%', 150) }}

+ +

This demo has exactly the same functionality as in the previous two sections, except that the {{htmlelement("button")}} element includes an inline onclick handler to make the function run when the button is pressed.

+ +

Please don't do this, however. It is bad practice to pollute your HTML with JavaScript, and it is inefficient — you'd have to include the onclick="createParagraph()" attribute on every button you wanted the JavaScript to apply to.

+ +

Using a pure JavaScript construct allows you to select all the buttons using one instruction. The code we used above to serve this purpose looks like this:

+ +
var buttons = document.querySelectorAll('button');
+
+for (var i = 0; i < buttons.length ; i++) {
+  buttons[i].addEventListener('click', createParagraph);
+}
+ +

This might look a bit longer than the onclick attribute, but this will work for all buttons no matter how many are on the page, and how many are added or removed. The JavaScript does not need to be changed.

+ +
+

Note: Try editing your version of apply-javascript.html and add a few more buttons into the file. When you reload, you should find that all of the buttons when clicked will create a paragraph. Neat, huh?

+
+ +

Comments

+ +

As with HTML and CSS, it is possible to write comments into your JavaScript code that will be ignored by the browser, and exist simply to provide instructions to your fellow developers on how the code works (and you, if you come back to your code after 6 months and can't remember what you did). Comments are very useful, and you should use them often, particularly for larger applications. There are two types:

+ + + +

So for example, we could annotate our last demo's JavaScript with comments like so:

+ +
// Function: creates a new paragraph and append it to the bottom of the HTML body.
+
+function createParagraph() {
+  var para = document.createElement('p');
+  para.textContent = 'You clicked the button!';
+  document.body.appendChild(para);
+}
+
+/*
+  1. Get references to all the buttons on the page and sort them in an array.
+  2. Loop through all the buttons and add a click event listener to each one.
+
+  When any button is pressed, the createParagraph() function will be run.
+*/
+
+var buttons = document.querySelectorAll('button');
+
+for (var i = 0; i < buttons.length ; i++) {
+  buttons[i].addEventListener('click', createParagraph);
+}
+ +

Summary

+ +

So there you go, your first step into the world of JavaScript. We've begun with just theory, to start getting you used to why you'd use JavaScript, and what kind of things you can do with it. Along the way you saw a few code examples and learned how JavaScript fits in with the rest of the code on your website, amongst other things.

+ +

JavaScript may seem a bit daunting right now, but don't worry — in this course we will take you through it in simple steps that will make sense going forward. In the next article we will plunge straight into the practical, getting you to jump straight in and build your own JavaScript examples.

+ +

In this module

+ + + +

{{NextMenu("Learn/JavaScript/First_steps/A_first_splash", "Learn/JavaScript/First_steps")}}

diff --git a/files/de/learn/javascript/index.html b/files/de/learn/javascript/index.html new file mode 100644 index 0000000000..78991e9102 --- /dev/null +++ b/files/de/learn/javascript/index.html @@ -0,0 +1,47 @@ +--- +title: JavaScript +slug: Learn/JavaScript +tags: + - Anfänger + - JavaScript +translation_of: Learn/JavaScript +--- +

{{Glossary('JavaScript')}} ist eine wichtige Webtechnologie, die es erlaubt, Webseiten interaktiv zu gestalten.

+ +

Wenn Ihr mehr als einfach nur eine Standard-Website erstellen wollt, solltet ihr wenigstens über JavaScript-Grundkenntnisse verfügen. 
+ Es ist nicht schwer, die Grundkenntnisse zu erlangen. Aber JavaScript ist eine sehr mächtige Technologie, die es euch erlaubt, komplexe Features zu verwenden - also gibt es keine Musterlösung, wie man diese Sprache erlernen kann
.
+ Wir empfehlen euch trotzdem, mit den nächsten Seiten anzufangen, um etwas mehr über JavaScript zu erfahren. 
+ Fangt von vorne an und lernt, bis ihr ganz hinten angekommen seid oder sucht euch einfach nur die Seite heraus, die ihr interessant findet. 

+ +
+
+

Die Grundsätze

+ +

Fangt hier an, falls ihr noch keine Erfahrungen mit JavaScript habt.

+ +
+
JavaScript Basics
+
JavaScript Basics zeigt euch, wie ihr anfangen könnt und gewährt euch Einblicke in die aufregende Welt von JavaScript.
+
JavaScript Guide
+
Falls Javascript noch Neuland für euch ist, wird euch dieser Guide Schritt für Schritt begleiten.
+
JavaScript Technologie-Überblick
+
EInführung zur weiten JavaScript-Landschaft.
+
Einführung zur Objekt-Orientierten Programmierung
+
Einführung in das Konzept von {{glossary("OOP","object-oriented programming")}} mit JavaScript.
+
+
+ +
+

Weiteres

+ +

Wenn ihr gefallen an JavaScript gefunden habt, gibt es hier einige Details, die euch interessieren könnten:

+ +
JavaScript Referenz
+ +
+
In unserer Referenz findet ihr Details zu jedem Aspekt von JavaScript: Event Handler, Operatoren, Statements und Funktionen.
+
+
+
+ +

 

diff --git a/files/de/learn/javascript/objects/basics/index.html b/files/de/learn/javascript/objects/basics/index.html new file mode 100644 index 0000000000..403f869034 --- /dev/null +++ b/files/de/learn/javascript/objects/basics/index.html @@ -0,0 +1,258 @@ +--- +title: JavaScript object basics +slug: Learn/JavaScript/Objects/Basics +translation_of: Learn/JavaScript/Objects/Basics +--- +
{{LearnSidebar}}
+ +
{{NextMenu("Learn/JavaScript/Objects/Object-oriented_JS", "Learn/JavaScript/Objects")}}
+ +

In diesem Artikel betrachten wir die fundamentale JavaScript Objekt Syntax und betrachten erneut einige JavaScript-Funktionalitäten, die im Kursverlauf bereits betrachtet wurden, immer im Hinblick darauf, dass viele der Merkmale, mit denen Sie bereits zu tun hatten, Objekte sind.

+ + + + + + + + + + + + +
Vorkenntnisse:Grundlegende Computerkenntnisse, ein grundlegendes Verständnis von HTML und CSS, Vertrautheit mit  JavaScript Grundlagen (siehe Erste Schritte und Bausteine).
Ziel:Verständnis für die grundlegende Theorie zur objektorientierten Programmierung, wie dies mit JavaScript zusammenhängt  ("fast alle Dinge sind Objekte") und wie man mit JavaScript-Objekten zu arbeiten beginnt.
+ +

Objekt Grundlagen

+ +

Ein Objekt ist eine Sammlung von zusammenhängenden Daten und/oder Funktionalitäten. Diese bestehen üblicherweise aus verschiedenen Variablen und Funktionen, die Eigenschaften und Methoden genannt werden, wenn sie sich innerhalb von Objekten befinden. Arbeiten wir ein Beispiel durch, um besser zu verstehen, wie ein Objekt aussieht.

+ +

Für den Anfang erzeugen wir eine lokale Kopie unserer Datei oojs.html. Sie enthält nur sehr wenig -  ein {{HTMLElement("script")}} Element, um unseren Quelltext einzufügen. Wir werden diese Datei bzw. dieses Beispiel als Basis nutzen, um die grundlegende Objektsyntax zu erforschen. Während der Arbeit an diesem Beispiel sollten Sie ihre  developer tools JavaScript console (z.B. Browser-Entwicklerwerkzeuge) geöffnet haben und bereit sein, einige Befehle einzutippen.

+ +

Wie mit vielen Dingen in JavaScript beginnt das Erzeugen eines Objekts häufig mit der Definition und Initialisierung einer Variablen. Versuchen Sie, folgendes unterhalb des bestehenden JavaScript Quelltextes einzugeben, dann abzuspeichern und einen Browser refresh durchzuführen:

+ +
var person = {};
+ +

Wenn Sie  person in ihrer JS console eingeben und die Entertaste drücken, sollten Sie folgendes Resultat erhalten:

+ +
[object Object]
+ +

Glückwunsch, Sie haben gerade ihr erstes Objekt erzeugt. Aufgabe erledigt! Aber dies ist ein leeres Objekt, also können wir noch nicht viel damit anfangen. Lassen sie uns unser Objekt erweitern, damit es folgendermaßen aussieht:

+ +
var person = {
+  name: ['Bob', 'Smith'],
+  age: 32,
+  gender: 'male',
+  interests: ['music', 'skiing'],
+  bio: function() {
+    alert(this.name[0] + ' ' + this.name[1] +
+    ' is ' + this.age + ' years old. He likes ' +
+    this.interests[0] + ' and ' + this.interests[1] + '.');
+  },
+  greeting: function() {
+    alert('Hi! I\'m ' + this.name[0] + '.');
+  }
+};
+
+ +

Nach dem Abspeichern und Aktualisieren des Browsers versuchen Sie, etwas vom Folgenden in der JavaScript-Konsole ihrer Browser Entwicklerwerkzeuge einzugeben:

+ +
person.name
+person.name[0]
+person.age
+person.interests[1]
+person.bio()
+person.greeting()
+ +

Sie haben nun einige Daten und Funktionen innerhalb ihres Objekts und sind in der Lage, mit recht einfacher Syntax darauf zuzugreifen!

+ +
+

Notiz: Wenn Sie Schwierigkeiten damit haben, dies zum Funktionieren zu bringen, versuchen Sie, Ihren Code mit unserer Version zu vergleichen - siehe  oojs-finished.html (zzgl. see it running live). Die Live Version wird eine leere Anzeige erzeugen - das ist so in Ordnung - öffnen Sie erneut die Entwicklerwerkzeuge [Mozilla Firefox: F12 -> Konsole] und versuchen Sie, die obigen Befehle einzugeben um die Objektstruktur zu betrachten.

+
+ +

Was passiert hier? Ein Objekt besteht aus vielen Elementen (engl. "Members", Anm. d. Übersetzers). Davon hat jedes einen Namen (z.B. name und age, wie oben) und einen Wert ( z.B. ['Bob', 'Smith' ] und 32). Jedes Name-Wert-Paar muss durch ein Komma getrennt sein und die jeweiligen Namen und Werte werden jeweils durch einen Doppelpunkt aufgeteilt. Die Syntax folgt stets diesem Muster:

+ +
var objectName = {
+  member1Name: member1Value,
+  member2Name: member2Value,
+  member3Name: member3Value
+};
+ +

Der Wert eines Objekt-Elements kann so ziemlich alles sein - in unserem person-Objekt haben wir einen String, eine Zahl, zwei Arrays und zwei Funktionen. Die ersten vier Elemente sind Datansätze und werden als Objekteigenschaften bezeichnet. Die letzten beiden Elemente sind Funktionen die es dem Objekt ermöglichen, etwas mit den Daten zu tun und werden als Methoden des Objekts bezeichnet.

+ +

Ein Objekt wie dieses bezeichnet man als Objektliteral — wir haben die Inhalte des Objekts wortwörtlich aufgeschrieben, als wir es erzeugt haben. Dies steht im Gegensatz zu solchen Objekten, die aus Klassen instanziert werden, welche wir später genauer betrachten werden.

+ +

Es ist durchaus üblich ein Objekt unter Verwendung eines Objektliterals zu erzeugen, wenn  man eine Reihe von strukturierten, zusammenhängenden Datensätzen auf gewisse Weise übertragen möchte. Zum Beispiel beim Senden einer Anfrage an einen Server, um diese in einer Datenbank abzuspeichern. Ein einzelnes Objekt zu senden ist viel effizienter, als viele Datensätze einzeln und darüber hinaus ist es einfacher, mit einem Array zu arbeiten, wenn man einzelne Datensätze anhand ihres Namens identifizieren möchte.

+ +

Punktnotation

+ +

Oben haben Sie auf die Eigenschaften und Methoden des Objektes mittels Punktnotation zugegriffen. Der Objektbezeichner person dient als Namensraum - dieser muss zuerst angegeben werden, um auf etwas zuzugreifen, das innerhalb des Objektes eingekapselt ist. Als nächstes folgt der Punkt und anschließend der Bestandteil, auf den Sie zugreifen wollen - dies kann der Name einer einfachen Eigenschaft sein, ein Element einer Arrayeigenschaft oder der Aufruf einer der Objektmethoden, zum Beispiel:

+ +
person.age
+person.interests[1]
+person.bio()
+ +

Sub-Namensräume

+ +

Es ist sogar möglich, den Wert eines Objekt-Members zu einem anderen Objekt umzuwandeln.

+ +

Versuchen Sie zum Beispiel, den "name" Member von

+ +
name: ['Bob', 'Smith'],
+ +

zu

+ +
name : {
+  first: 'Bob',
+  last: 'Smith'
+},
+ +

zu ändern. Hier erzeugen wir effektiv einen Sub-Namensraum. Das hört sich kompliziert an, ist es aber nicht - um auf diese Inhalte zuzugreifen, müssen Sie bloß den zusätzlichen Namensraum, getrennt durch einen Punkt, hinzufügen. Versuchen Sie folgendes in der JS Konsole:

+ +
person.name.first
+person.name.last
+ +

Wichtig: An diesem Punkt müssen Sie ihre Methodendeklarationen umarbeiten und Instanzen von

+ +
name[0]
+name[1]
+ +

zu

+ +
name.first
+name.last
+ +

ändern. Sonst greifen die Methoden ins Leere.

+ +

Klammer-Notation

+ +

Es gibt einen weiteren Weg, auf Objekteigenschaften zuzugreifen - durch Benutzung der Klammern-Notation. Statt dies zu schreiben:

+ +
person.age
+person.name.first
+ +

Schreibt man:

+ +
person['age']
+person['name']['first']
+ +

Dies gleicht der Art wie man auf Arrayelemente zugreift und ist im Grunde der gleiche Vorgang - statt einen Index zu nutzen, um ein Element auszuwählen, benutzt man den den Namen der mit jedem Memberwert assoziiert wird. Es wundert daher nicht, dass Objekte manchmal assoziative Arrays genannt werden - sie verknüpfen Zeichenketten mit Werten in der gleichen Weise, wie ein Array Indizes mit Werten verknüpft.

+ +

Wertzuweisungen an Objekt-Elemente

+ +

Bisher haben wir nur betrachtet, wie man Objekt-Elemente abruft ( getting ) — man kann den Wert von Objektelementen auch setzen ( updating ), indem man das Element, welches gesetzt werden soll, folgendermaßen deklariert:

+ +
person.age = 45;
+person['name']['last'] = 'Cratchit';
+ +

Versuchen Sie, die Zeilen wie oben aufgeführt einzugeben und dann die Elemente wieder abzurufen, etwa so:

+ +
person.age
+person['name']['last']
+ +

Zuweisungen hören nicht beim Ändern von Werten existierender Eigenschaften und Methoden auf, man kann auch völlig neue Elemente erzeugen. Versuchen Sie dies in der JS Konsole:

+ +
person['eyes'] = 'hazel';
+person.farewell = function() { alert("Bye everybody!"); }
+ +

Sie können diese neuen Elemente nun ausprobieren:

+ +
person['eyes']
+person.farewell()
+ +

Ein nützlicher Aspekt der Klammer-Notation ist jener, dass man nicht nur Elementwerte dynamisch zuweisen kann, sondern auch Elementnamen. Nehmen wir an, wir wollen es Usern ermöglichen, selbstdefinierte Wertetypen in ihren people-Daten zu speichern, indem sie den Elementnamen und Wert in zwei Textfeldern eingeben. Wir könnten diese Werte so abrufen:

+ +
var myDataName = nameInput.value;
+var myDataValue = nameValue.value;
+ +

dann könnten wir diesen neuen Elementnamen und Wert zum person-Objekt so hinzufügen:

+ +
person[myDataName] = myDataValue;
+ +

Um das auszuprobieren, versuchen Sie, folgendes in ihren Quelltext einzufügen, gleich unterhalb der schliessenden, geschweiften Klammer des person-Objekts:

+ +
var myDataName = 'height';
+var myDataValue = '1.75m';
+person[myDataName] = myDataValue;
+ +

Nach dem Abspeichern und einem Browser-Refresh geben Sie folgendes in der Konsole ein:

+ +
person.height
+ +

Eine Eigenschaft zu einem Objekt hinzuzufügen ist mit der Punkt-Notation nicht möglich. Diese akzeptiert nur einen literalen Elementnamen, keine Variable, die auf einen Namen zeigt.

+ +

Was bedeutet "this"?

+ +

Sie haben vielleicht schon etwas seltsames in unseren Methoden bemerkt. Sehen wir uns zum Beispiel folgendes genauer an:

+ +
greeting: function() {
+  alert('Hi! I\'m ' + this.name.first + '.');
+}
+ +

Sie wundern sich wahrscheinlich, was dieses "this" sein soll. Das Schlüsselwort this referenziert das derzeitige Objekt, in dem der Code hineingeschrieben wurde - in diesem Fall wäre this gleichbedeutend mit person. Also warum nicht einfach stattdessen person schreiben? Wie Sie im Artikel  Object-oriented JavaScript for beginners sehen werden, wenn wir damit beginnen, z.B. Konstruktoren zu erzeugen usw.: this ist sehr nützlich - es wird immer sicherstellen, dass die korrekten Werte verwendet werden, wenn sich der Kontext eines Elementes ändert (z.B. zwei unterschiedliche Objektinstanzen von person haben andere Namenswerte und sollten folgerichtig ihren jeweiligen Namenswert verwenden, wenn die greeting Methode aufgerufen wird).

+ +

Lassen Sie uns dies an einem vereinfachten Paar Objekten vom Typ person verdeutlichen:

+ +
var person1 = {
+  name: 'Chris',
+  greeting: function() {
+    alert('Hi! I\'m ' + this.name + '.');
+  }
+}
+
+var person2 = {
+  name: 'Brian',
+  greeting: function() {
+    alert('Hi! I\'m ' + this.name + '.');
+  }
+}
+ +

In diesem Fall wird person1.greeting()  "Hi! I'm Chris." ausgeben; person2.greeting() wiederum wird  "Hi! I'm Brian." ausgeben, obwohl der Quelltext in jedem Fall genau gleich lautet. Wie schon gesagt,  this  ist gleichbedeutend mit dem Objekt, in dem sich der Quelltext befindet - das ist nicht sehr nützlich, wenn man Objektliterale händisch schreibt, aber es ist sehr hilfreich, sobald Objekte dynamisch erzeugt werden (zum Beispiel unter Verwendung von Konstruktoren). Es wird im weiteren Verlauf alles deutlich werden.

+ +

Sie haben die ganze Zeit Objekte verwendet

+ +

Als Sie diese Beispiele durchgegangen sind, haben Sie wahrscheinlich gedacht, dass die Punktnotation, die Sie verwendet haben, sehr vertraut scheint. Es liegt daran, dass Sie diese im gesamten Kursverlauf benutzt haben. Jedes Mal, wenn wir ein Beispiel behandelten, welches Teile des built-in Browser API oder JavaScript-Objekte verwendete, haben wir Objekte verwendet, da solche Funktionalitäten genau mit der gleichen Art von Objektstrukturen aufgebaut werden, wie wir sie hier betrachtet haben. Diese sind allerdings etwas komplexer als die unserer eigenen, einfachen Beispiele.

+ +

Wenn Sie String-Methoden wie diese verwenden,

+ +
myString.split(',');
+ +

haben Sie eine Methode verwendet, die eine Instanz der String-Klasse zur Verfügung stellte. Jedes Mal, wenn Sie einen String in ihrem Quelltext erstellen, wir dieser String automatisch als eine Instanz von String erzeugt, dadurch stehen einige allgemeine Methoden und Eigenschaften zur Verfügung.

+ +

Wenn Sie im DOM folgende Zeilen verwenden,

+ +
var myDiv = document.createElement('div');
+var myVideo = document.querySelector('video');
+ +

haben Sie Methoden verwendet, die von einer Instanz der Klasse Document zur Verfügung gestellt wurden. Für jede geladene Webseite wird eine Instanz von Document erzeugt, die document genannt wird, welche die gesamte Struktur, den Inhalt und weitere Merkmale wie die URL repräsentiert. Dies bedeutet wiederum, dass einige allgemeine Methoden und Eigenschaften entsprechend verfügbar gemacht werden.

+ +

Das gleiche gilt für so ziemlich jedes andere built-in Objekt/API, welches Sie benutzt haben  — z.B. Array, Math, usw.

+ +

Beachten Sie, dass built-in Objekte/APIs nicht zwangsläufig immer automatisch eine Objektinstanz erzeugen. Ein Beispiel, die  Notifications API — welche es modernen Browsern erlaubt, System Notifikationen zu generieren  — benötigt für jede zu sendende Notifikation eine neue Objektinstanz, die Sie durch Verwendung des Konstruktors erzeugen müssen. Versuchen Sie, folgendes in Ihrer JavaScript Konsole einzugeben:

+ +
var myNotification = new Notification('Hello!');
+ +

Konstruktoren werden wir in einem späteren Artikel detaillierter behandeln.

+ +
+

Bemerkung: Es ist nützlich, sich die Art, wie Objekte kommunizieren, als Nachrichtenweitergabe vorzustellen — wenn ein Objekt die Ausführung einer Aktion von einem anderen Objekt benötigt, wird es meist eine Nachricht an dieses Objekt mittels einer seiner Methoden senden und auf eine Antwort warten, welche wir als Rückgabewert bezeichnen.

+
+ +

Zusammenfassung

+ +

Glückwunsch, Sie haben das Ende unseres ersten JS Objekt Artikels erreicht —Sie sollten nun eine gute Vorstellung davon haben, wie man mit Objekten in JavaScript arbeitet — einschließlich der Erzeugung von eigenen, einfachen Objekte. Sie sollten auch zu schätzen wissen, dass Objekte als Daten- und Funktionsspeicherstrukturen sehr nützlich sind — wenn Sie versuchen würden, alle Eigenschaften und Methoden in unserem person-Objekt als einzelne Variablen bzw. Funktionen nachzuverfolgen, wäre das sehr ineffizient und frustrierend und wir würden riskieren, das gleichnamige Variablen kollidieren. Objekte lassen uns Informationen gefahrlos und sicher in ihrem jeweils eigenen Paket verstauen.

+ +

Im nächsten Artikel werden wir damit beginnen, uns die Theorie der objektorientierten Programmierung (OOP) anzusehen und wie solche Techniken in JavaScript umgesetzt werden können.

+ +

{{NextMenu("Learn/JavaScript/Objects/Object-oriented_JS", "Learn/JavaScript/Objects")}}

+ +

In diesem Modul

+ + diff --git a/files/de/learn/javascript/objects/index.html b/files/de/learn/javascript/objects/index.html new file mode 100644 index 0000000000..9178a14f6d --- /dev/null +++ b/files/de/learn/javascript/objects/index.html @@ -0,0 +1,53 @@ +--- +title: Introducing JavaScript objects +slug: Learn/JavaScript/Objects +tags: + - Beginner + - Guide + - JavaScript + - Objects + - Objekte + - Programmieren + - Prototypes + - Tutorial +translation_of: Learn/JavaScript/Objects +--- +
{{LearnSidebar}}
+ +

In JavaScript sind die meisten Dinge Objekte die auf dem Grundstein von JavaScript aufgebaut worden sind. Hierzu zählen Strings, Arrays welche mittels der API grundlegend fundamentiert sind. Du kannst auch deine eigenen Objekte definieren um Dinge aus der Realität in Programmcode wiederzuverwenden. Die objektorientierte Programmierung ist wichtig um ein komplettes Verständnis zu bekommen als auch die Sprache wirklich zu verstehen. Aus diesem Grund stellen wir euch einige Lernmodule an um besser in das Thema einsteigen zu können.
+
+ Aber hier wollen wir euch erstmal erklären, was ein Objekt genau ist und wie die Syntax für eine Definition eines Objektes ist.

+ +

Voraussetzungen

+ +

Bevor du mit diesem Lernmodul beginnst, solltest du dich mit HTML und CSS vertraut gemacht haben. Solltest du noch keine Vorkenntnisse haben, so sehe dir bitte Einführung in HTML und Einführung in CSS an bevor du mit JavaScript beginnst.

+ +

Auch solltest du dich vorher mit den Grundlagen von JavaScript vertraut gemacht haben, sie dazu bitte in folgenden Modulen nach: JavaScript: Erste Schritte und JavaScript: Elementare Grundlagen.

+ +
+

Hinweis: Solltest du an einem Computer arbeiten, der dir das Erstellen und Bearbeiten von Dateien nicht erlaubt, so kannst du Dienste wie JSBin oder Thimble für diesen Kurs nutzen.

+
+ +

Guides

+ +
+
Objekt Grundlagen
+
In diesem ersten Kaptiel erklären wir euch wie ein Objekt fundamental aufgebaut ist, als auch die Syntax zu diesem. Wir behandeln außerdem einige Gebiete, die wir schon bereits gesehen haben, denn die meisten Dinge in JavaScript mit denen du arbeiten wirst sind Objekte.
+
Objektorientiertes JavaScript für Anfänger
+
Hier zeigen wir euch die objektorientierte Programmierung (OOP/OOJS) - hier gibt es erste Einblicke wie du dein Objekt am besten definierst und dann zeigen wir dir, wie JavaScript dein Objekt zum Leben bringt durch Instanziierung.
+
Objekt Prototypes
+
Prototypes ist der Begriff für den Vorgang für die weitergehende Verwendung eines Objektes mit vererbbaren Funktionen. Solltest du bereits eine andere objektorientierte Programmiersprache benutzt haben, wirst du merken, dass JavaScript anders funktioniert. In dem Modul behandeln wir außerdem wie die Verkettung von Prototypen funktioniert und schauen uns die Eigenschaften eines Objektes genauer an, mit denen wir auch die Funktionen definieren werden.
+
Vererbung in JavaScript
+
Nachdem du in den vorherigen Lernmodulen einiges über OOJS gelernt hast, zeigen wir dir hier wie du Funktionen und Eigenschaften mit einem anderen Objekt vererbben kannst.
+
Arbeiten mit JSON Strukturen
+
JavaScript Object Notation (JSON) ist eine textbasierte Struktursprache um Daten kompakt und wiederverwendbar zu machen. Diese Struktursprache ist die gängigste in JavaScript um Objekte zu beschreiben, speichern oder für andere Dienste verfügbar zu machen.
+
Objekte an einer Übung definieren
+
In dieser Übung möchten wir nochmal alle vorherigen Themen aufgreifen und nochmal mit der Syntax von Objekten üben und dabei etwas Spaß mit springenden, bunten Bällen haben.
+
+ +

Übungen

+ +
+
Erstelle neue Funktionen für springende Bälle
+
In dieser Übung greifen wir uns das Demo-Projekt aus dem vorherigen Artikel nochmal auf und werden die springenden Bälle mit neuen Objektfunktionen erweitern.
+
diff --git a/files/de/learn/javascript/objects/inheritance/index.html b/files/de/learn/javascript/objects/inheritance/index.html new file mode 100644 index 0000000000..827dda17f6 --- /dev/null +++ b/files/de/learn/javascript/objects/inheritance/index.html @@ -0,0 +1,440 @@ +--- +title: Inheritance in JavaScript +slug: Learn/JavaScript/Objects/Inheritance +translation_of: Learn/JavaScript/Objects/Inheritance +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/Objects/Object_prototypes", "Learn/JavaScript/Objects/JSON", "Learn/JavaScript/Objects")}}
+ +

Nachdem nun die schmutzigen Details des OOJS erklärt sind, beschäftigt sich dieser Artikel damit, wie "Kinder"-Objektklassen (Konstruktoren) Features von ihren "Eltern"-Klassen vererbt bekommen. Zusätzlich stellen wir Hinweise dazu bereit, wann und wo Du OOJS am besten anwendest und wie mit Klassen im modern ECMAScript Syntax umgegangen wird.

+ + + + + + + + + + + + +
Voraussetzungen:Grundsätzliche EDV-Kenntnisse, ein grundlegendes Verständnis für HTML und CSS, mit JavaScript Grundlagen vertraut sein (siehe Erste Schritte und Building blocks) und Grundlagen zu OOJS (sieheIntroduction to objects).
Lernziel:Zu verstehen, wie es in JavaScript möglich ist, Vererbung zu implementieren.
+ +

Prototypal inheritance

+ +

So far we have seen some inheritance in action — we have seen how prototype chains work, and how members are inherited going up a chain. But mostly this has involved built-in browser functions. How do we create an object in JavaScript that inherits from another object?

+ +

Let's explore how to do this with a concrete example.

+ +

Getting started

+ +

First of all, make yourself a local copy of our oojs-class-inheritance-start.html file (see it running live also). Inside here you'll find the same Person() constructor example that we've been using all the way through the module, with a slight difference — we've defined only the properties inside the constructor:

+ +
function Person(first, last, age, gender, interests) {
+  this.name = {
+    first,
+    last
+  };
+  this.age = age;
+  this.gender = gender;
+  this.interests = interests;
+};
+ +

The methods are all defined on the constructor's prototype. For example:

+ +
Person.prototype.greeting = function() {
+  alert('Hi! I\'m ' + this.name.first + '.');
+};
+ +
+

Note: In the source code, you'll also see bio() and farewell() methods defined. Later you'll see how these can be inherited by other constructors.

+
+ +

Say we wanted to create a Teacher class, like the one we described in our initial object-oriented definition, which inherits all the members from Person, but also includes:

+ +
    +
  1. A new property, subject — this will contain the subject the teacher teaches.
  2. +
  3. An updated greeting() method, which sounds a bit more formal than the standard greeting() method — more suitable for a teacher addressing some students at school.
  4. +
+ +

Defining a Teacher() constructor function

+ +

The first thing we need to do is create a Teacher() constructor — add the following below the existing code:

+ +
function Teacher(first, last, age, gender, interests, subject) {
+  Person.call(this, first, last, age, gender, interests);
+
+  this.subject = subject;
+}
+ +

This looks similar to the Person constructor in many ways, but there is something strange here that we've not seen before — the call() function. This function basically allows you to call a function defined somewhere else, but in the current context. The first parameter specifies the value of this that you want to use when running the function, and the other parameters are those that should be passed to the function when it is invoked.

+ +

We want the Teacher() constructor to take the same parameters as the Person() constructor it is inheriting from, so we specify them all as parameters in the call() invocation.

+ +

The last line inside the constructor simply defines the new subject property that teachers are going to have, which generic people don't have.

+ +

As a note, we could have simply done this:

+ +
function Teacher(first, last, age, gender, interests, subject) {
+  this.name = {
+    first,
+    last
+  };
+  this.age = age;
+  this.gender = gender;
+  this.interests = interests;
+  this.subject = subject;
+}
+ +

But this is just redefining the properties anew, not inheriting them from Person(), so it defeats the point of what we are trying to do. It also takes more lines of code.

+ +

Inheriting from a constructor with no parameters

+ +

Note that if the constructor you are inheriting from doesn't take its property values from parameters, you don't need to specify them as additional arguments in call(). So, for example, if you had something really simple like this:

+ +
function Brick() {
+  this.width = 10;
+  this.height = 20;
+}
+ +

You could inherit the width and height properties by doing this (as well as the other steps described below, of course):

+ +
function BlueGlassBrick() {
+  Brick.call(this);
+
+  this.opacity = 0.5;
+  this.color = 'blue';
+}
+ +

Note that we've only specified this inside call() — no other parameters are required as we are not inheriting any properties from the parent that are set via parameters.

+ +

Setting Teacher()'s prototype and constructor reference

+ +

All is good so far, but we have a problem. We have defined a new constructor, and it has a prototype property, which by default just contains an object with a reference to the constructor function itself. It does not contain the methods of the Person constructor's prototype property. To see this, enter Object.getOwnPropertyNames(Teacher.prototype) into either the text input field or your JavaScript console. Then enter it again, replacing Teacher with Person. Nor does the new constructor inherit those methods. To see this, compare the outputs of Person.prototype.greeting and Teacher.prototype.greeting. We need to get Teacher() to inherit the methods defined on Person()'s prototype. So how do we do that?

+ +
    +
  1. Add the following line below your previous addition: +
    Teacher.prototype = Object.create(Person.prototype);
    + Here our friend create() comes to the rescue again. In this case we are using it to create a new object and make it the value of Teacher.prototype. The new object has Person.prototype as its prototype and will therefore inherit, if and when needed, all the methods available on Person.prototype.
  2. +
  3. We need to do one more thing before we move on. After adding the last line, Teacher.prototype's constructor property is now equal to Person(), because we just set Teacher.prototype to reference an object that inherits its properties from Person.prototype! Try saving your code, loading the page in a browser, and entering Teacher.prototype.constructor into the console to verify.
  4. +
  5. This can become a problem, so we need to set this right. You can do so by going back to your source code and adding the following line at the bottom: +
    Object.defineProperty(Teacher.prototype, 'constructor', {
    +    value: Teacher,
    +    enumerable: false, // so that it does not appear in 'for in' loop
    +    writable: true });
    +
  6. +
  7. Now if you save and refresh, entering Teacher.prototype.constructor should return Teacher(), as desired, plus we are now inheriting from Person()!
  8. +
+ +

Giving Teacher() a new greeting() function

+ +

To finish off our code, we need to define a new greeting() function on the Teacher() constructor.

+ +

The easiest way to do this is to define it on Teacher()'s prototype — add the following at the bottom of your code:

+ +
Teacher.prototype.greeting = function() {
+  let prefix;
+
+  if (this.gender === 'male' || this.gender === 'Male' || this.gender === 'm' || this.gender === 'M') {
+    prefix = 'Mr.';
+  } else if (this.gender === 'female' || this.gender === 'Female' || this.gender === 'f' || this.gender === 'F') {
+    prefix = 'Ms.';
+  } else {
+    prefix = 'Mx.';
+  }
+
+  alert('Hello. My name is ' + prefix + ' ' + this.name.last + ', and I teach ' + this.subject + '.');
+};
+ +

This alerts the teacher's greeting, which also uses an appropriate name prefix for their gender, worked out using a conditional statement.

+ +

Trying the example out

+ +

Now that you've entered all the code, try creating an object instance from Teacher() by putting the following at the bottom of your JavaScript (or something similar of your choosing):

+ +
let teacher1 = new Teacher('Dave', 'Griffiths', 31, 'male', ['football', 'cookery'], 'mathematics');
+ +

Now save and refresh, and try accessing the properties and methods of your new teacher1 object, for example:

+ +
teacher1.name.first;
+teacher1.interests[0];
+teacher1.bio();
+teacher1.subject;
+teacher1.greeting();
+teacher1.farewell();
+ +

These should all work just fine. The queries on lines 1, 2, 3, and 6 access members inherited from the generic Person() constructor (class). The query on line 4 accesses a member that is available only on the more specialized Teacher() constructor (class). The query on line 5 would have accessed a member inherited from Person(), except for the fact that Teacher() has its own member with the same name, so the query accesses that member.

+ +
+

Note: If you have trouble getting this to work, compare your code to our finished version (see it running live also).

+
+ +

The technique we covered here is not the only way to create inheriting classes in JavaScript, but it works OK, and it gives you a good idea about how to implement inheritance in JavaScript.

+ +

You might also be interested in checking out some of the new {{glossary("ECMAScript")}} features that allow us to do inheritance more cleanly in JavaScript (see Classes). We didn't cover those here, as they are not yet supported very widely across browsers. All the other code constructs we discussed in this set of articles are supported as far back as IE9 or earlier, and there are ways to achieve earlier support than that.

+ +

A common way is to use a JavaScript library — most of the popular options have an easy set of functionality available for doing inheritance more easily and quickly. CoffeeScript for example provides class, extends, etc.

+ +

A further exercise

+ +

In our OOP theory section, we also included a Student class as a concept, which inherits all the features of Person, and also has a different greeting() method from Person that is much more informal than the Teacher's greeting. Have a look at what the student's greeting looks like in that section, and try implementing your own Student() constructor that inherits all the features of Person(), and implements the different greeting() function.

+ +
+

Note: If you have trouble getting this to work, have a look at our finished version (see it running live also).

+
+ +

Object member summary

+ +

To summarize, you've got four types of property/method to worry about:

+ +
    +
  1. Those defined inside a constructor function that are given to object instances. These are fairly easy to spot — in your own custom code, they are the members defined inside a constructor using the this.x = x type lines; in built in browser code, they are the members only available to object instances (usually created by calling a constructor using the new keyword, e.g. let myInstance = new myConstructor()).
  2. +
  3. Those defined directly on the constructor themselves, that are available only on the constructor. These are commonly only available on built-in browser objects, and are recognized by being chained directly onto a constructor, not an instance. For example, Object.keys(). These are also known as static properties/methods.
  4. +
  5. Those defined on a constructor's prototype, which are inherited by all instances and inheriting object classes. These include any member defined on a Constructor's prototype property, e.g. myConstructor.prototype.x().
  6. +
  7. Those available on an object instance, which can either be an object created when a constructor is instantiated like we saw above (so for example var teacher1 = new Teacher( name = 'Chris' ); and then teacher1.name), or an object literal (let teacher1 = { name = 'Chris' } and then teacher1.name).
  8. +
+ +

If you are not sure which is which, don't worry about it just yet — you are still learning, and familiarity will come with practice.

+ +

ECMAScript 2015 Classes

+ +

ECMAScript 2015 introduces class syntax to JavaScript as a way to write reusable classes using easier, cleaner syntax, which is more similar to classes in C++ or Java. In this section we'll convert the Person and Teacher examples from prototypal inheritance to classes, to show you how it's done.

+ +
+

Note: This modern way of writing classes is supported in all modern browsers, but it is still worth knowing about the underlying prototypal inheritance in case you work on a project that requires supporting a browser that doesn't support this syntax (most notably Internet Explorer).

+
+ +

Let's look at a rewritten version of the Person example, class-style:

+ +
class Person {
+  constructor(first, last, age, gender, interests) {
+    this.name = {
+      first,
+      last
+    };
+    this.age = age;
+    this.gender = gender;
+    this.interests = interests;
+  }
+
+  greeting() {
+    console.log(`Hi! I'm ${this.name.first}`);
+  };
+
+  farewell() {
+    console.log(`${this.name.first} has left the building. Bye for now!`);
+  };
+}
+
+ +

The class statement indicates that we are creating a new class. Inside this block, we define all the features of the class:

+ + + +

We can now instantiate object instances using the new operator, in just the same way as we did before:

+ +
let han = new Person('Han', 'Solo', 25, 'male', ['Smuggling']);
+han.greeting();
+// Hi! I'm Han
+
+let leia = new Person('Leia', 'Organa', 19, 'female', ['Government']);
+leia.farewell();
+// Leia has left the building. Bye for now
+
+ +
+

Note: Under the hood, your classes are being converted into Prototypal Inheritance models — this is just syntactic sugar. But I'm sure you'll agree that it's easier to write.

+
+ +

Inheritance with class syntax

+ +

Above we created a class to represent a person. They have a series of attributes that are common to all people; in this section we'll create our specialized Teacher class, making it inherit from Person using modern class syntax. This is called creating a subclass or subclassing.

+ +

To create a subclass we use the extends keyword to tell JavaScript the class we want to base our class on,

+ +
class Teacher extends Person {
+  constructor(subject, grade) {
+    this.subject = subject;
+    this.grade = grade;
+  }
+}
+ +

but there's a little catch.

+ +

Unlike old-school constructor functions where the new operator does the initialization of this to a newly-allocated object, this isn't automatically initialized for a class defined by the extends keyword, i.e the sub-classes.

+ +

Therefore running the above code will give an error:

+ +
Uncaught ReferenceError: Must call super constructor in derived class before
+accessing 'this' or returning from derived constructor
+ +

For sub-classes, the this intialization to a newly allocated object is always dependant on the parent class constructor, i.e the constructor function of the class from which you're extending.

+ +

Here we are extending the Person class — the Teacher sub-class is an extension of the Person class. So for Teacher, the this initialization is done by the Person constructor.

+ +

To call the parent constructor we have to use the super() operator, like so:

+ +
class Teacher extends Person {
+  constructor(subject, grade) {
+    super(); // Now 'this' is initialized by calling the parent constructor.
+    this.subject = subject;
+    this.grade = grade;
+  }
+}
+ +

There is no point having a sub-class if it doesn't inherit properties from the parent class.
+ It is good then, that the super() operator also accepts arguments for the parent constructor.

+ +

Looking back to our Person constructor, we can see it has the following block of code in its constructor method:

+ +
 constructor(first, last, age, gender, interests) {
+   this.name = {
+     first,
+     last
+   };
+   this.age = age;
+   this.gender = gender;
+   this.interests = interests;
+} 
+ +

Since the super() operator is actually the parent class constructor, passing it the necessary arguments of the Parent class constructor will also initialize the parent class properties in our sub-class, thereby inheriting it:

+ +
class Teacher extends Person {
+  constructor(first, last, age, gender, interests, subject, grade) {
+    super(first, last, age, gender, interests);
+
+    // subject and grade are specific to Teacher
+    this.subject = subject;
+    this.grade = grade;
+  }
+}
+
+ +

Now when we instantiate Teacher object instances, we can call methods and properties defined on both Teacherand Person as we'd expect:

+ +
let snape = new Teacher('Severus', 'Snape', 58, 'male', ['Potions'], 'Dark arts', 5);
+snape.greeting(); // Hi! I'm Severus.
+snape.farewell(); // Severus has left the building. Bye for now.
+snape.age // 58
+snape.subject; // Dark arts
+
+ +

Like we did with Teachers, we could create other subclasses of Person to make them more specialized without modifying the base class.

+ +
+

Note: You can find this example on GitHub as es2015-class-inheritance.html (see it live also).

+
+ +

Getters and Setters

+ +

There may be times when we want to change the values of an attribute in the classes we create or we don't know what the final value of an attribute will be. Using the Teacher example, we may not know what subject the teacher will teach before we create them, or their subject may change between terms.

+ +

We can handle such situations with getters and setters.

+ +

Let's enhance the Teacher class with getters and setters. The class starts the same as it was the last time we looked at it.

+ +

Getters and setters work in pairs. A getter returns the current value of the variable and its corresponding setter changes the value of the variable to the one it defines.

+ +

The modified Teacher class looks like this:

+ +
class Teacher extends Person {
+  constructor(first, last, age, gender, interests, subject, grade) {
+    super(first, last, age, gender, interests);
+    // subject and grade are specific to Teacher
+    this._subject = subject;
+    this.grade = grade;
+  }
+
+  get subject() {
+    return this._subject;
+  }
+
+  set subject(newSubject) {
+    this._subject = newSubject;
+  }
+}
+
+ +

In our class above we have a getter and setter for the subject property. We use _ to create a separate value in which to store our name property. Without using this convention, we would get errors every time we called get or set. At this point:

+ + + +

The example below shows the two features in action:

+ +
// Check the default value
+console.log(snape.subject) // Returns "Dark arts"
+
+// Change the value
+snape.subject = "Balloon animals" // Sets _subject to "Balloon animals"
+
+// Check it again and see if it matches the new value
+console.log(snape.subject) // Returns "Balloon animals"
+
+ +
+

Note: You can find this example on GitHub as es2015-getters-setters.html (see it live also).

+
+ +
+

Note: Getters and setters can be very useful at times, for example when you want to run some code every time a property is requested or set. For simple cases, however, plain property access without a getter or setter will do just fine.

+
+ +

When would you use inheritance in JavaScript?

+ +

Particularly after this last article, you might be thinking "woo, this is complicated". Well, you are right. Prototypes and inheritance represent some of the most complex aspects of JavaScript, but a lot of JavaScript's power and flexibility comes from its object structure and inheritance, and it is worth understanding how it works.

+ +

In a way, you use inheritance all the time. Whenever you use various features of a Web API , or methods/properties defined on a built-in browser object that you call on your strings, arrays, etc., you are implicitly using inheritance.

+ +

In terms of using inheritance in your own code, you probably won't use it often, especially to begin with, and in small projects. It is a waste of time to use objects and inheritance just for the sake of it when you don't need them. But as your code bases get larger, you are more likely to find a need for it. If you find yourself starting to create a number of objects that have similar features, then creating a generic object type to contain all the shared functionality and inheriting those features in more specialized object types can be convenient and useful.

+ +
+

Note: Because of the way JavaScript works, with the prototype chain, etc., the sharing of functionality between objects is often called delegation. Specialized objects delegate functionality to a generic object type.

+
+ +

When using inheritance, you are advised to not have too many levels of inheritance, and to keep careful track of where you define your methods and properties. It is possible to start writing code that temporarily modifies the prototypes of built-in browser objects, but you should not do this unless you have a really good reason. Too much inheritance can lead to endless confusion, and endless pain when you try to debug such code.

+ +

Ultimately, objects are just another form of code reuse, like functions or loops, with their own specific roles and advantages. If you find yourself creating a bunch of related variables and functions and want to track them all together and package them neatly, an object is a good idea. Objects are also very useful when you want to pass a collection of data from one place to another. Both of these things can be achieved without use of constructors or inheritance. If you only need a single instance of an object, then you are probably better off just using an object literal, and you certainly don't need inheritance.

+ +

Alternatives for extending the prototype chain

+ +

In JavaScript, there are several different ways to extend the prototype of an object aside from what we've shown above. To find out more about the other ways, visit our Inheritance and the prototype chain article.

+ +

Test your skills!

+ +

You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see Test your skills: Object-oriented JavaScript.

+ +

Summary

+ +

This article has covered the remainder of the core OOJS theory and syntax that we think you should know now. At this point you should understand JavaScript object and OOP basics, prototypes and prototypal inheritance, how to create classes (constructors) and object instances, add features to classes, and create subclasses that inherit from other classes.

+ +

In the next article we'll have a look at how to work with JavaScript Object Notation (JSON), a common data exchange format written using JavaScript objects.

+ +

See also

+ + + +

{{PreviousMenuNext("Learn/JavaScript/Objects/Object_prototypes", "Learn/JavaScript/Objects/JSON", "Learn/JavaScript/Objects")}}

+ +

In this module

+ + diff --git a/files/de/learn/javascript/objects/json/index.html b/files/de/learn/javascript/objects/json/index.html new file mode 100644 index 0000000000..7b01bfbf52 --- /dev/null +++ b/files/de/learn/javascript/objects/json/index.html @@ -0,0 +1,345 @@ +--- +title: Arbeiten mit JSON +slug: Learn/JavaScript/Objects/JSON +translation_of: Learn/JavaScript/Objects/JSON +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/Objects/Inheritance", "Learn/JavaScript/Objects/Object_building_practice", "Learn/JavaScript/Objects")}}
+ +

Die JavaScript Object Notation (JSON) ist ein standardisiertes, textbasiertes Format, um strukturierte Daten auf Basis eines JavaScript Objekts darzustellen. Es wird häufig für die Übertragung von Daten in Webanwendungen verwendet (z.B. das Senden einiger Daten vom Server zum Client, damit sie auf einer Webseite angezeigt werden können oder umgekehrt). Es wird dir sehr häufig über den Weg laufen, daher geben wir dir in diesem Artikel alles mit, damit du JSON mithilfe von JavaScript nutzen kannst, einschließlich des Umwandelns von JSON, damit du auf die enthaltenen Daten zugreifen und JSON erstellen kannst.

+ + + + + + + + + + + + +
Voraussetzungen:Grundlegende Computerkenntnisse, grundlegendes Verständnis von HTML, CSS und JavaScript (siehe First steps und Building blocks) sowie OOJS Grundkenntnisse (siehe Introduction to objects).
Ziele:Zu verstehen, wie man mit Daten im JSON-Format arbeitet und eigene JSON-Objekte erstellt.
+ +

Nein, im ernst, was ist JSON?

+ +

{{glossary("JSON")}} ist ein textbasierendes Datenformat angelehnt an die JavaScript Object Syntax und popularisiert durch Douglas Crockford. Auch wenn es der JavaScript Object Syntax ähnelt, ist es dennoch Javascript unabhängig. Heutzutage unterstützen zahlreiche Programmierumgebungen JSON, sowohl lesend (parse) als auch schreibend.

+ +

JSON existiert als eine Zeichenkette (String) — das ist nützlich, um Daten über das Netzwerk zu übermitteln. Es muss in ein natives JavaScript Objekt umgewandelt werden, wenn du auf die Daten zugreifen willst. Das ist kein großes Ding — JavaScript stellt ein globales JSON-Objekt zur Verfügung, das Methoden zur Konvertierung zwischen den beiden zur Verfügung stellt.

+ +
+

Note: Eine Zeichenkette in ein natives Objekt umzuwandeln nennt man parsing, wohingegen die Umwandlung eines nativen Objekts in eine Zeichenkette, um es im Netzwerk zu übermitteln, stringification genannt wird.

+
+ +

Ein JSON Objekt kann als einfache  Textdatei mit der Endung .json gespeichert werden oder einen {{glossary("MIME type")}} als application/json.

+ +

JSON Struktur

+ +

Wie bereits erwähnt, ist JSON ein textbasierendes Datenformat angelehnt an die JavaScript Object Syntax. Es können sowohl in JSON als auch in JavaScript Objekten die gleichen Datentypen verwendet werden  — Strings, Zahlen, Arrays, Booleans und andere Objekttypen. Das erlaubt es dir, eine Datenhierarchie zu erstellen. Z.B.:

+ +
{
+  "squadName": "Super hero squad",
+  "homeTown": "Metro City",
+  "formed": 2016,
+  "secretBase": "Super tower",
+  "active": true,
+  "members": [
+    {
+      "name": "Molecule Man",
+      "age": 29,
+      "secretIdentity": "Dan Jukes",
+      "powers": [
+        "Radiation resistance",
+        "Turning tiny",
+        "Radiation blast"
+      ]
+    },
+    {
+      "name": "Madame Uppercut",
+      "age": 39,
+      "secretIdentity": "Jane Wilson",
+      "powers": [
+        "Million tonne punch",
+        "Damage resistance",
+        "Superhuman reflexes"
+      ]
+    },
+    {
+      "name": "Eternal Flame",
+      "age": 1000000,
+      "secretIdentity": "Unknown",
+      "powers": [
+        "Immortality",
+        "Heat Immunity",
+        "Inferno",
+        "Teleportation",
+        "Interdimensional travel"
+      ]
+    }
+  ]
+}
+ +

Würden wir das Objekt in ein JavaScript Programm laden und die Variable superHeroes auslesen, könnten wir die Objektdaten mittels der gleichen dot/bracket notation abrufen, wie in diesem Artikel behandelt: JavaScript object basics. Zum Beispiel:

+ +
superHeroes.homeTown
+superHeroes['active']
+ +

Um Daten in tieferen hierarchischen Ebenen abrufen zu können, müssen die benötigten Eigenschaften und Array-indizes aneinandergereiht werden.  Um beispielsweise die dritte superpower des zweiten hero in der members Liste abrufen zu können, würdest du sowas machen:

+ +
superHeroes['members'][1]['powers'][2]
+ +
    +
  1. Zuerst haben wir den Variablennamen — superHeroes.
  2. +
  3. Darin wollen wir die members Eigenschaft abrufen, also benutzen wir["members"].
  4. +
  5. members beinhaltet ein Array mit Objekten. Wir wollen das zweite Objekt innerhalb des Arrays abrufen, also benutzen wir [1].
  6. +
  7. Innerhalb des Objekts wollen wir die powers Eigenschaft abrufen, demnach benutzen wir ["powers"].
  8. +
  9. Die powers Eigenschaft ist ein Array, welches die gewählten superpowers der heroes hält. Wir wollen die dritte superpower, also [2].
  10. +
+ +
+

Note: Wir haben euch das zuvor erwähnte JSON in einer Variable in unserem JSONTest.html Beispiel (siehe source code) zur Verfügung gestellt. Versuche es hochzuladen und die Daten in der Variable mittels der JavaScript Konsole deines Browser's abzurufen.

+
+ +

Arrays als JSON

+ +

Eben haben wir angemerkt, dass JSON Text im Grunde wie ein JavaScript object aussieht, und das ist weitestgehend richtig. "Weitestgehend" da ein Array eben gültiges(valid) JSON darstellt, zum Beispiel:

+ +
[
+  {
+    "name": "Molecule Man",
+    "age": 29,
+    "secretIdentity": "Dan Jukes",
+    "powers": [
+      "Radiation resistance",
+      "Turning tiny",
+      "Radiation blast"
+    ]
+  },
+  {
+    "name": "Madame Uppercut",
+    "age": 39,
+    "secretIdentity": "Jane Wilson",
+    "powers": [
+      "Million tonne punch",
+      "Damage resistance",
+      "Superhuman reflexes"
+    ]
+  }
+]
+ +

Dieses Arrays ist komplett gültges JSON. Die Array Elemente müssen lediglich beginnend mit des Array's Index - z.B. [0]["powers"][0] - abgerufen werden.

+ +

 Anmerkungen

+ + + +

Aktives Lernen: Arbeiten mithilfe eines JSON Beispiels

+ +

Lasst uns durch ein Beispiel durcharbeiten um zu veranschaulichen wie wir mit JSON Daten auf einer Webseite arbeiten können.

+ +

Los Geht's

+ +

Anfangs, mache lokale Kopien unserer heroes.html und style.css Dateien. Letztere enthält ein paar einfache CSS Elemente um unsere Seite ein wenig zu stylen, während die Erste einen einfachen HTML body enthält:

+ +
<header>
+</header>
+
+<section>
+</section>
+ +

Und ein {{HTMLElement("script")}} Element, welches den JavaScript Code halten wird, den wir etwas später erstellen werden. Momentan existieren nur zwei Zeilen, welche auf das {{HTMLElement("header")}} und {{HTMLElement("section")}} Element referenzieren und sie in Variablen speichern:

+ +
var header = document.querySelector('header');
+var section = document.querySelector('section');
+ +

Wir haben unsere JSON Daten auf unserem GitHub Account veröffentlicht: https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json.

+ +

Wir laden es in unsere Seite und benutzen geschickt die DOM Manipulation um es so darzustellen:

+ +

+ +

JSON erhalten

+ +

Um JSON zu erhalten, werden wir unsere API, genannt {{domxref("XMLHttpRequest")}} (oft XHR genannt), benutzen. Es handelt sich um ein sehr nützliches JavaScript Objekt, das es uns erlaubt, Netzwerkabfragen auszuführen um Ressourcen eines Servers via JavaScript (e.g. Bilder, Text, JSON, sogar HTML snippets) zu erhalten. So können wir kleine Sektionen mit Inhalt aktualisieren ohne die komplette Seite neuzuladen. Das führt zu responsiveren Webseiten und klingt ziemlich spannend. Allerdings fällt es außerhalb des hier behandelten Themas um es ausführlicher zu erklären.

+ +
    +
  1. Zuerst werden wir die JSON URL die wir abrufen möchten in einer Variable speichern. Füge Folgendes zum Ende deines JavaScript Codes hinzu: +
    var requestURL = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json';
    +
  2. +
  3. Um eine Abfrage zu erstellen, müssen wir eine neue Objekt-Abfrage-Instanz des XMLHttpRequest constructors mit dem Keyword new erstellen. Füge Folgenden Code hinzu: +
    var request = new XMLHttpRequest();
    +
  4. +
  5. Nun müssen wir eine neue Abfrage mit der open() Methode eröffnen. Füge Folgenden Code hinzu: +
    request.open('GET', requestURL);
    + +

    Die Methode braucht mindestens zwei Parameter — wobei es weitere optionale Parameter gibt. Für dieses Beispiel werden wir uns jedoch nur den einfachen, zwingend erforderlichen Parametern widmen :

    + +
      +
    • Die HTTP Methode die für die Netzwerkabfrage erforderlich ist. In diesem Fall reicht GET aus, da wir ja nur simple Daten erhalten wollen .
    • +
    • Die Ziel-URL — Die JSON URL die wir zuvor in der requestURL Variable gespeichert haben.
    • +
    +
  6. +
  7. Füge als Nächstes folgende Zeilen hinzu — hier setzen wir den responseType auf JSON, sodass XHR weiß, dass der Server JSON zurückgeben und im Hintergrund in ein JavaScript Objekt konvertiert werden soll. Anschließend versenden wir die Abfrage mit der  send() Methode: +
    request.responseType = 'json';
    +request.send();
    +
  8. +
  9. Zu guter Letzt müssen wir auf die Antwort des Servers (response) warten und sie anschließend weiterverarbeiten. Füge folgenden Code hinter deinem bisherigen Code hinzu: +
    request.onload = function() {
    +  var superHeroes = request.response;
    +  populateHeader(superHeroes);
    +  showHeroes(superHeroes);
    +}
    +
  10. +
+ +

Hier speichern wir die Response zu unserer Abfrage (verfügbar in der response Eigenschaft) in einer Variable namens: superHeroes; Diese Variable enthält nun das JavaScript Objekt basieren auf dem JSON! Nun geben wir das Objekt an zwei Funktionsaufrufe weiter— der erste wird den <header> mit korrekte Daten füllen, während der zweite einen Informationssteckbrief eines jeden Helden im Team erstellt und es in die <section>einfügt.

+ +

Wir packen den Code in einen Eventhandler der ausgeführt wird, sobald das load event auf das Request Objekt angestoßen wird (siehe onload) — das passiert, da das load Event angestoßen wird sobald die response erfolgreich zurückgegeben wurde. Das garantiert, dass request.response definitiv verfügbar sein wird, wenn wir damit etwas machen wollen.

+ +

Populating the header

+ +

Wir haben also die JSON Daten bekommen und in ein JavaScript Objekt konvertiert. Nun arbeiten wir damit und schreiben zwei Funktionen. Als Erstes, füge folgende Funktion unter deinen bisherigen Code:

+ +
function populateHeader(jsonObj) {
+  var myH1 = document.createElement('h1');
+  myH1.textContent = jsonObj['squadName'];
+  header.appendChild(myH1);
+
+  var myPara = document.createElement('p');
+  myPara.textContent = 'Hometown: ' + jsonObj['homeTown'] + ' // Formed: ' + jsonObj['formed'];
+  header.appendChild(myPara);
+}
+ +

Wir haben den Parameter jsonObj aufgerufen, um uns daran zu erinnern, dass das JavaScript Objekt seinen Ursprung in JSON hat. Wir erstellen zunächst ein {{HTMLElement("h1")}} element with createElement(), set its textContent to equal the squadName property of the object, then append it to the header using appendChild(). We then do a very similar operation with a paragraph: create it, set its text content and append it to the header. The only difference is that its text is set to a concatenated string containing both the homeTown and formed properties of the object.

+ +

Creating the hero information cards

+ +

Next, add the following function at the bottom of the code, which creates and displays the superhero cards:

+ +
function showHeroes(jsonObj) {
+  var heroes = jsonObj['members'];
+
+  for (var i = 0; i < heroes.length; i++) {
+    var myArticle = document.createElement('article');
+    var myH2 = document.createElement('h2');
+    var myPara1 = document.createElement('p');
+    var myPara2 = document.createElement('p');
+    var myPara3 = document.createElement('p');
+    var myList = document.createElement('ul');
+
+    myH2.textContent = heroes[i].name;
+    myPara1.textContent = 'Secret identity: ' + heroes[i].secretIdentity;
+    myPara2.textContent = 'Age: ' + heroes[i].age;
+    myPara3.textContent = 'Superpowers:';
+
+    var superPowers = heroes[i].powers;
+    for (var j = 0; j < superPowers.length; j++) {
+      var listItem = document.createElement('li');
+      listItem.textContent = superPowers[j];
+      myList.appendChild(listItem);
+    }
+
+    myArticle.appendChild(myH2);
+    myArticle.appendChild(myPara1);
+    myArticle.appendChild(myPara2);
+    myArticle.appendChild(myPara3);
+    myArticle.appendChild(myList);
+
+    section.appendChild(myArticle);
+  }
+}
+ +

To start with, we store the members property of the JavaScript object in a new variable. This array contains multiple objects that contain the information for each hero.

+ +

Next, we use a for loop to loop through each object in the array. For each one, we:

+ +
    +
  1. Create several new elements: an <article>, an <h2>, three <p>s, and a <ul>.
  2. +
  3. Set the <h2> to contain the current hero's name.
  4. +
  5. Fill the three paragraphs with their secretIdentity, age, and a line saying "Superpowers:" to introduce the information in the list.
  6. +
  7. Store the powers property in another new variable called superPowers — this contains an array that lists the current hero's superpowers.
  8. +
  9. Use another for loop to loop through the current hero's superpowers — for each one we create a <li> element, put the superpower inside it, then put the listItem inside the <ul> element (myList) using appendChild().
  10. +
  11. The very last thing we do is to append the <h2>, <p>s, and <ul> inside the <article> (myArticle), then append the <article> inside the <section>. The order in which things are appended is important, as this is the order they will be displayed inside the HTML.
  12. +
+ +
+

Note: If you are having trouble getting the example to work, try referring to our heroes-finished.html source code (see it running live also.)

+
+ +
+

Note: If you are having trouble following the dot/bracket notation we are using to access the JavaScript object, it can help to have the superheroes.json file open in another tab or your text editor, and refer to it as you look at our JavaScript. You should also refer back to our JavaScript object basics article for more information on dot and bracket notation.

+
+ +

Converting between objects and text

+ +

The above example was simple in terms of accessing the JavaScript object, because we set the XHR request to convert the JSON response directly into a JavaScript object using:

+ +
request.responseType = 'json';
+ +

But sometimes we aren't so lucky — sometimes we'll receive a raw JSON string, and we'll need to convert it to an object ourselves. And when we want to send a JavaScript object across the network, we'll need to convert it to JSON (a string) before sending. Luckily, these two problems are so common in web development that a built-in JSON object is available in browsers, which contains the following two methods:

+ + + +

You can see the first one in action in our heroes-finished-json-parse.html example (see the source code) — this does exactly the same thing as the example we built up earlier, except that we set the XHR to return the raw JSON text, then used parse() to convert it to an actual JavaScript object. The key snippet of code is here:

+ +
request.open('GET', requestURL);
+request.responseType = 'text'; // now we're getting a string!
+request.send();
+
+request.onload = function() {
+  var superHeroesText = request.response; // get the string from the response
+  var superHeroes = JSON.parse(superHeroesText); // convert it to an object
+  populateHeader(superHeroes);
+  showHeroes(superHeroes);
+}
+ +

As you might guess, stringify() works the opposite way. Try entering the following lines into your browser's JavaScript console one by one to see it in action:

+ +
var myJSON = { "name": "Chris", "age": "38" };
+myJSON
+var myString = JSON.stringify(myJSON);
+myString
+ +

Here we're creating a JavaScript object, then checking what it contains, then converting it to a JSON string using stringify() — saving the return value in a new variable — then checking it again.

+ +

Summary

+ +

In this article, we've given you a simple guide to using JSON in your programs, including how to create and parse JSON, and how to access data locked inside it. In the next article, we'll begin looking at object-oriented JavaScript.

+ +

See also

+ + + +

{{PreviousMenuNext("Learn/JavaScript/Objects/Inheritance", "Learn/JavaScript/Objects/Object_building_practice", "Learn/JavaScript/Objects")}}

+ +

 

+ +

In this module

+ + + +

 

diff --git a/files/de/learn/javascript/objects/object-oriented_js/index.html b/files/de/learn/javascript/objects/object-oriented_js/index.html new file mode 100644 index 0000000000..b4229a8058 --- /dev/null +++ b/files/de/learn/javascript/objects/object-oriented_js/index.html @@ -0,0 +1,290 @@ +--- +title: Objektorientiertes JavaScript für Beginner +slug: Learn/JavaScript/Objects/Object-oriented_JS +tags: + - Anfänger + - Artikel + - Erstellen + - Erzeugen + - Instanzen + - JavaScript + - Konstruktor + - Lernen + - OOJS + - OOP + - Objekt + - Objektorientiert + - codescripting +translation_of: Learn/JavaScript/Objects/Object-oriented_JS +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/Objects/Basics", "Learn/JavaScript/Objects/Object_prototypes", "Learn/JavaScript/Objects")}}
+ +

Mit den nun bereits erlangten Grundlagen werden wir uns jetzt auf objektorientiertes JavaScript (OOJS) konzentrieren - dieser Artikel vermittelt Grundlagen der Theorie der objektorientierten Programmierung (OOP). Anschließend wird näher betrachtet, wie JavaScript Objektklassen über Konstruktor-Funktionen emuliert und wie Objekt-Instanzen erzeugt werden.

+ + + + + + + + + + + + +
Voraussetzungen: +

Grundlegende Computerkenntnisse, ein grundlegendes Verständnis von HTML und CSS, Vertrautheit mit den Grundlagen von JavaScript (siehe erste Schritte und Bausteine) und OOJS-Grundlagen (siehe Einführung in Objekte).

+
Ziel:Die grundlegende Theorie hinter der objektorientierten Programmierung und wie diese in JavaScript umgesetzt ist ("alles ist ein Objekt") zu verstehen, und wie man Konstruktoren und Objektinstanzen erstellt.
+ +

Objektorientierte Programmierung - Grundlagen

+ +

Um zu beginnen möchten wir Ihnen eine vereinfachende und umfangreiche Übersicht darüber geben, was objektorientierte Programmierung (OOP) ist. Wir sagen vereinfachend, weil OOP schnell sehr kompliziert werden kann und an dieser Stelle eine vollständige Einführung sehr wahrscheinlich mehr verwirren als helfen würde. Die Grundidee von OOP ist, dass wir Objekte verwenden, um Dinge aus der realen Welt zu modellieren, die wir in unseren Programmen abbilden wollen und/oder eine einfache Möglichkeit bieten möchten, auf Funktionen zuzugreifen, die sonst nur schwer oder gar nicht genutzt werden könnten.

+ +

Objekte können in Beziehung stehende Daten und Code enthalten, die Informationen über die Sache darstellen, die Sie modellieren möchten, sowie Funktionalitäten bzw. Verhalten, die Sie erhalten bzw. bereitstellen möchten. Objektdaten (und oft auch Funktionen) können geordnet (das Fachwort dafür lautet "gekapselt") innerhalb eines Objektpakets gespeichert werden (dem ein bestimmter Name gegeben werden kann, auf den man sich beziehen kann, der manchmal auch "Namensraum" genannt wird), wodurch es leicht strukturiert und zugänglich wird. Objekte werden auch häufig als Datenspeicher verwendet, die einfach über das Netzwerk gesendet werden können.

+ +

Definieren einer Objektvorlage

+ +

Betrachten wir ein einfaches Programm, das Informationen über die Schüler und Lehrer einer Schule anzeigt. Hier betrachten wir die OOP-Theorie im Allgemeinen, nicht im Zusammenhang mit einer bestimmten Programmiersprache.

+ +

Um damit zu beginnen, könnten wir zu unserem person-Objekt aus dem vorhergehenden Kapitel zurückkehren, in dem wir Informationen und Funktionalitäten einer Person definiert hatten. Es gibt viele Dinge, die man über eine Person wissen kann (ihre Adresse, Größe, Schuhgröße, DNA-Profil, Ausweisnummer, signifikante Persönlichkeitsmerkmale ...), aber in diesem Fall sind wir nur daran interessiert, ihren Namen, ihr Alter, ihr Geschlecht und ihre Interessen zu betrachten. Und wir wollen auch in der Lage sein, eine kurze Erläuterung über sie auf der Grundlage dieser Daten zu schreiben und sie dazu zu bringen, "Hallo" zu sagen. Dies wird als "Abstraktion" bezeichnet - ein einfaches Modell einer komplexeren Sache wird erstellt, das die wichtigsten Aspekte in einer Weise darstellt, die für die Zwecke unseres Programms leicht zu bearbeiten sind.

+ +

+ +

Erstellen von realen Objekten

+ +

Von unserer Klasse können wir Objektinstanzen erstellen - Objekte die Informationen und Funktionalitäten enthalten, die in der Klasse definiert worden. Von unserer Klasse person können wir nun einige tatsächliche Personen erzeugen:

+ +

+ +

Wenn eine Objektinstanz aus einer Klasse erzeugt wurde, wird die Konstruktorfunktion der Klasse ausgeführt, um die Objektinstanz zu erzeugen. Dieser Vorgang der Erzeugung einer Objektinstanz aus einer Klasse wird als Instanziierung bezeichnet - die Objektinstanz wird von der Klasse aus instanziiert.

+ +

Spezialisierte Klassen

+ +

In diesem Fall wollen wir keine allgemeinen Leute - wir wollen Lehrer und Schüler, die beide spezifischere Typen von Menschen sind. In OOP können wir neue Klassen erstellen, die auf anderen Klassen basieren - diese neuen Unterklassen können die Daten- und Funktionalitäten ihrer Elternklasse erben, so dass Sie die Funktionalitäten, die allen Objekttypen gemeinsam ist, wiederverwenden können, anstatt sie duplizieren zu müssen.  Da wo sich Funktionalitäten zwischen den Klassen unterscheiden soll, können bei Bedarf spezialisierte Features direkt in den betroffenen Klassen entsprechend definieren.

+ +

+ +

Das ist wirklich sehr nützlich - Lehrer und Schüler haben viele gemeinsame Merkmale wie Name, Geschlecht und Alter, so dass es praktisch ist, diese Merkmale nur einmal zu definieren. Sie können dasselbe Merkmal auch separat in verschiedenen Klassen definieren, da jede Definition dieses Merkmals in einem anderen Namensraum liegt. Die Begrüßung eines Schülers könnte z.B. die Form "Yo, ich bin firstName" haben (z.B. Yo, ich bin Sam), während ein Lehrer etwas formelleres verwenden könnte, wie z.B. "Hallo, mein Name ist prefix lastName und ich unterrichte Subject". (z.B. Hallo, ich heiße Mr. Griffiths und unterrichte Chemie).

+ +
+

Hinweis: Das Fachwort für die Fähigkeit, mehrere Objekttypen mit der gleichen Funktionalität zu implementieren, nennt man Polymorphismus. Nur für den Fall, dass Sie sich das fragen.

+
+ +

Sie können nun Objektinstanzen aus Ihren Unterklassen erzeugen. Beispiel:

+ +

+ +

Im weiteren Verlauf dieses Kapitels werden wir uns damit beschäftigen, wie die OOP-Theorie in JavaScript in die Praxis umgesetzt werden kann.

+ +

Konstruktoren und Objektinstanzen

+ +

JavaScript verwendet spezielle Funktionen, die "Konstruktor-Funktionen" genannt werden, um Objekte und deren Eigenschaften zu definieren und zu initialisieren. Sie sind nützlich, weil Sie oft auf Situationen stoßen werden, in denen Sie nicht wissen, wie viele Objekte Sie erstellen werden müssen. Konstruktoren bieten die Möglichkeit, so viele Objekte wie nötig auf einfache und effektive Weise zu erstellen, indem sie alle erforderlichen Daten und Funktionen an diese Objekte anhängen.

+ +

Lassen Sie uns nun das Erstellen von Klassen über Konstruktoren und das Erstellen von Objektinstanzen aus ihnen heraus speziell in JavaScript untersuchen. Zuerst möchten wir Sie bitten, eine neue lokale Kopie der oojs.html-Datei zu erstellen, die wir im vorhergehenden Kapitel bereits benutzt haben.

+ +

Ein einfaches Beispiel

+ +
    +
  1. Fangen wir damit an, wie man eine Person mit einer normalen Funktion definieren könnte. Fügen Sie diese Funktion innerhalb des Skript-Elements der oojs.html hinzu: +
    function createNewPerson(name) {
    +  var obj = {};
    +  obj.name = name;
    +  obj.greeting = function() {
    +    alert('Hi! I\'m ' + obj.name + '.');
    +  };
    +  return obj;
    +}
    +
  2. +
  3. Sie können nun eine neue Person erstellen, indem Sie diese Funktion aufrufen - bitte geben Sie die folgenden Zeilen in der JavaScript-Konsole Ihres Browsers ein: +
    var salva = createNewPerson('Salva');
    +salva.name;
    +salva.greeting();
    + Das funktioniert zwar ganz gut, aber es ist ein bisschen umständlich. Wenn wir wissen, dass wir ein Objekt erstellen wollen, warum müssen wir dann explizit ein neues leeres Objekt erstellen und es zurückgeben? Glücklicherweise bietet uns JavaScript eine praktische Vereinfachung in Form von Konstruktorfunktionen - nutzen wir jetzt eine!
  4. +
  5. Ersetzen Sie die vorher implementierte Funktion durch folgende: +
    function Person(name) {
    +  this.name = name;
    +  this.greeting = function() {
    +    alert('Hi! I\'m ' + this.name + '.');
    +  };
    +}
    +
  6. +
+ +

Die Konstruktorfunktion ist die JavaScript-Version einer Klasse. Sie werden feststellen, dass sie alle Eigenschaften hat, die man in einer Funktion erwartet, obwohl sie weder etwas zurückgibt oder explizit ein Objekt erzeugt - sie definiert im Grunde nur Eigenschaften und Methoden. Sie werden sehen, dass dieses Schlüsselwort auch hier verwendet wird - es besagt im Grunde, dass immer dann, wenn eine dieser Objektinstanzen erzeugt wird, die Eigenschaft name des Objekts gleich dem Namenswert ist, der an den Konstruktoraufruf übergeben wird, und die Methode greeting() wird ebenfalls den Namenswert verwenden, der an den Konstruktoraufruf übergeben wird.

+ +
+

Hinweis: Der Name einer Konstruktorfunktion beginnt normalerweise mit einem Großbuchstaben - diese Konvention wird verwendet, um Konstruktorfunktionen im Code leichter erkennbar zu machen.

+
+ +

Wie rufen wir also einen Konstruktor auf, um einige Objekte zu erstellen?

+ +
    +
  1. Fügen Sie die folgenden Zeilen unterhalb Ihres vorherigen Codezusatzes ein: +
    var person1 = new Person('Bob');
    +var person2 = new Person('Sarah');
    +
  2. +
  3. Speichern Sie Ihren Code, laden Sie ihn im Browser neu und geben Sie die folgenden Zeilen in Ihre JS-Konsole ein: +
    person1.name
    +person1.greeting()
    +person2.name
    +person2.greeting()
    +
  4. +
+ +

Cool! Sie werden nun sehen, dass wir zwei neue Objekte auf der Seite haben, die jeweils unter einem anderen Namespace gespeichert sind - wenn Sie auf ihre Eigenschaften und Methoden zugreifen, müssen Sie Aufrufe mit person1 oder person2 starten; die darin enthaltene Funktionalität ist sauber verpackt, damit sie nicht mit anderen Funktionen kollidiert. Sie haben jedoch die gleiche Namenseigenschaft und die gleiche Methode greeting() zur Verfügung. Beachten Sie, dass Sie Ihren eigenen Namenswert verwenden, der Ihnen bei der Erstellung zugewiesen wurde. Das ist ein Grund, warum es sehr wichtig ist, diesen zu verwenden, so dass Sie Ihre eigenen Werte verwenden werden, und nicht irgendeinen anderen Wert.

+ +

Sehen wir uns die Konstruktoraufrufe noch einmal genauer an:

+ +
var person1 = new Person('Bob');
+var person2 = new Person('Sarah');
+ +

In jedem Fall wird das neue Schlüsselwort verwendet, um dem Browser mitzuteilen, dass wir eine neue Objektinstanz erstellen wollen, gefolgt vom Funktionsnamen mit den erforderlichen Parametern in Klammern. Das Ergebnis wird in einer Variablen gespeichert - sehr ähnlich wie bei dem Aufruf einer Standardfunktion. Jede Instanz wird entsprechend dieser Definition erzeugt:

+ +
function Person(name) {
+  this.name = name;
+  this.greeting = function() {
+    alert('Hi! I\'m ' + this.name + '.');
+  };
+}
+ +

Nach dem Anlegen der neuen Objekte enthalten die Variablen person1 und person2 die folgenden Objekte:

+ +
{
+  name: 'Bob',
+  greeting: function() {
+    alert('Hi! I\'m ' + this.name + '.');
+  }
+}
+
+{
+  name: 'Sarah',
+  greeting: function() {
+    alert('Hi! I\'m ' + this.name + '.');
+  }
+}
+ +

Beachten Sie, dass wir beim Aufruf unserer Konstruktor-Funktion jedes Mal greeting() definieren, was nicht ideal ist. Um dies zu vermeiden, können wir stattdessen Funktionen auf dem Prototypen definieren, die wir uns später genauer ansehen werden.

+ +

Erstellen unseres finalen Konstruktors

+ +

Das Beispiel, das wir oben betrachtet haben, war nur ein einfaches Beispiel, um den Einstieg zu erleichtern. Lassen Sie uns nun weitermachen und unsere finale Konstruktor-Funktion Person() erstellen.

+ +
    +
  1. Entfernen Sie den bisher eingefügten Code und fügen Sie nachfolgenden Konstruktor als Ersatz hinzu - dies ist im Prinzip genau dasselbe, wie das einfache Beispiel, nur etwas komplexer: +
    function Person(first, last, age, gender, interests) {
    +  this.name = {
    +     first : first,
    +     last : last
    +  };
    +  this.age = age;
    +  this.gender = gender;
    +  this.interests = interests;
    +  this.bio = function() {
    +    alert(this.name.first + ' ' + this.name.last + ' is ' + this.age + ' years old. He likes ' + this.interests[0] + ' and ' + this.interests[1] + '.');
    +  };
    +  this.greeting = function() {
    +    alert('Hi! I\'m ' + this.name.first + '.');
    +  };
    +}
    +
  2. +
  3. Fügen Sie nun unter dem Code von oben folgende Zeile ein, um eine Objektinstanz zu erzeugen: +
    var person1 = new Person('Bob', 'Smith', 32, 'male', ['music', 'skiing']);
    +
  4. +
+ +

Sie werden nun sehen, dass Sie auf die Eigenschaften und Methoden zugreifen können, genau wie wir es zuvor getan haben - probieren Sie das in Ihrer JS-Konsole aus:

+ +
person1['age']
+person1.interests[1]
+person1.bio()
+// etc.
+ +
+

Hinweis: Wenn Sie Probleme haben, dies zum Laufen zu bringen, vergleichen Sie Ihren Code mit unserer Version - siehe oojs-class-finished.html (hier können Sie auch sehen, wie es live läuft).

+
+ +

Weitere Übungen

+ +

Versuchen Sie zunächst, ein paar weitere eigene Objekte hinzuzufügen, und versuchen Sie, die Eigenschaften bzw. Funktionen der daraus erzeugten Objektinstanzen zu nutzen bzw. zu verändern.

+ +

Außerdem gibt es einige Probleme mit unserer bio()-Methode - die Ausgabe enthält immer das Pronomen "He", egal ob Ihre Person weiblich ist oder einem anderen Geschlecht angehört. Und die bio()-Methode wird nur zwei Interessen enthalten, auch wenn mehr im Interessen-Array aufgelistet sind. Finden Sie heraus, wie man das in der Klassendefinition (Konstruktor) beheben kann? Sie können jeden beliebigen Code in einen Konstruktor einfügen (Sie werden wahrscheinlich ein paar Bedingungen und eine Schleife benötigen). Überlegen Sie sich, wie die Sätze je nach Geschlecht und je nachdem, ob die Anzahl der aufgelisteten Interessen 1, 2 oder mehr als 2 beträgt, unterschiedlich strukturiert werden sollten.

+ +
+

Hinweis: Wenn Sie nicht weiterkommen, haben wir eine Antwort bzw. Lösung in unserem GitHub-Repo bereitgestellt (Sehen Sie es sich hier an) - versuchen Sie bitte aber erst einmal, die Lösung selbst zu schreiben!

+
+ +

Andere Möglichkeiten, Objektinstanzen zu erzeugen

+ +

Bisher haben wir zwei verschiedene Wege gesehen, um eine Objektinstanz zu erzeugen - die Deklaration eines Objektes als Literal und die Verwendung einer Konstruktorfunktion (siehe oben).

+ +

Diese machen Sinn, aber es gibt auch andere Wege - wir möchten Sie mit diesen vertraut machen, falls Sie auf Ihren Reisen im Web auf sie stoßen sollten.

+ +

Der Object()-Konstruktor

+ +

Zuerst können Sie den Object() Konstruktor verwenden, um ein neues Objekt zu erstellen. Ja, sogar generische Objekte haben einen Konstruktor, der ein leeres Objekt erzeugt.

+ +
    +
  1. Geben Sie dies in die JavaScript-Konsole Ihres Browsers ein: +
    var person1 = new Object();
    +
  2. +
  3. Diese speichert ein leeres Objekt in der Variable person1. Sie können dann diesem Objekt Eigenschaften und Methoden mit Punkt- oder Klammer-Notation hinzufügen, wie gewünscht. Versuchen Sie diese Beispiele in Ihrer Konsole: +
    person1.name = 'Chris';
    +person1['age'] = 38;
    +person1.greeting = function() {
    +  alert('Hi! I\'m ' + this.name + '.');
    +};
    +
  4. +
  5. Sie können auch ein Objektliteral als Parameter an den Object() Konstruktor übergeben, um es mit Eigenschaften/Methoden vorzufüllen. Versuchen Sie folgendes in Ihrer JS-Konsole: +
    var person1 = new Object({
    +  name: 'Chris',
    +  age: 38,
    +  greeting: function() {
    +    alert('Hi! I\'m ' + this.name + '.');
    +  }
    +});
    +
  6. +
+ +

Verwendung der Methode create()

+ +

Konstruktoren können Ihnen helfen, Ihren Code zu ordnen - Sie können Konstruktoren an einer Stelle erstellen und dann bei Bedarf Instanzen davon erstellen - und es ist immer nachvollziehbar, woher sie kommen.

+ +

Einige Leute ziehen es jedoch vor, Objektinstanzen zu erstellen, ohne vorher Konstruktoren zu erstellen, insbesondere wenn sie nur wenige Instanzen eines Objekts erstellen müssen. JavaScript hat eine eingebaute Methode namens create(), die es Ihnen einfach ermöglicht, dies zu tun. Mit ihr können Sie ein neues Objekt auf Basis eines beliebigen vorhandenen Objekts erstellen.

+ +
    +
  1. Wenn Ihre fertige Übung aus den vorherigen Abschnitten im Browser geladen ist, versuchen Sie folgendes in Ihrer JavaScript-Konsole: +
    var person2 = Object.create(person1);
    +
  2. +
  3. Nun geben Sie bitte folgendes in die JavaScript-Konsole ein: +
    person2.name
    +person2.greeting()
    +
  4. +
+ +

Sie werden sehen, dass person2 auf der Basis von person1 erstellt wurde - es hat die gleichen Eigenschaften und die gleiche Methode, die ihm zur Verfügung stehen.

+ +

Eine Einschränkung von create() ist, dass der IE8 es nicht unterstützt. Daher können Konstruktoren effektiver sein, wenn Sie ältere Browser unterstützen wollen.

+ +

Wir werden die Auswirkungen von create() später noch genauer untersuchen.

+ +

Zusammenfassung

+ +

Dieser Artikel hat eine vereinfachte Sicht der objektorientierten Theorie geliefert - das ist noch lange nicht die ganze Geschichte, aber er gibt Ihnen eine Vorstellung davon, womit wir es hier zu tun haben. Darüber hinaus haben wir damit begonnen, verschiedene Möglichkeiten der Erzeugung von Objektinstanzen zu betrachten.

+ +

Im nächsten Artikel werden wir uns mit JavaScript-Objekt-Prototypen beschäftigen.

+ +

{{PreviousMenuNext("Learn/JavaScript/Objects/Basics", "Learn/JavaScript/Objects/Object_prototypes", "Learn/JavaScript/Objects")}}

+ +

In diesem Modul

+ + diff --git a/files/de/learn/javascript/objects/object_prototypes/index.html b/files/de/learn/javascript/objects/object_prototypes/index.html new file mode 100644 index 0000000000..010c5986e9 --- /dev/null +++ b/files/de/learn/javascript/objects/object_prototypes/index.html @@ -0,0 +1,288 @@ +--- +title: Object prototypes +slug: Learn/JavaScript/Objects/Object_prototypes +tags: + - Anfänger + - Beitrag + - 'I10n:priority' + - JavaScript + - Konstruktor + - Lernen + - OOJS + - OOP + - Objekt + - Prototypen + - Prototypketten + - codescripting + - create() +translation_of: Learn/JavaScript/Objects/Object_prototypes +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/Objects/Object-oriented_JS", "Learn/JavaScript/Objects/Inheritance", "Learn/JavaScript/Objects")}}
+ +

Prototypen dienen als Mechanismus, durch den JavaScript-Objekte Eigenschaften voneinander erben. In diesem Artikel erklären wir, wie Prototypketten funktionieren und betrachten, wie die Prototypeneigenschaft verwendet werden kann, um Methoden zu bestehenden Konstruktoren hinzuzufügen.

+ + + + + + + + + + + + +
Voraussetzungen: +

Verständnis der Funktionen in JavaScript, sowie Vertrautheit mit den Grundlagen von JavaScript (siehe erste Schritte und Bausteine) und OOJS-Grundlagen (siehe Einführung in Objekte).

+
Ziel:JavaScript-Objekt-Prototypen zu verstehen, wie Prototypenketten funktionieren und wie man neue Methoden auf die Prototyp-Eigenschaft hinzufügt.
+ +

Eine Prototyp-basierte Sprache?

+ +

JavaScript wird oft als eine prototypische bzw. Prototyp-basierte Sprache beschrieben - um Vererbung zu ermöglichen, können Objekte dazu ein Prototyp-Objekt haben, das als Vorlageobjekt fungiert, von dem es Methoden und Eigenschaften erbt. Das Prototyp-Objekt eines Objekts kann auch ein Prototyp-Objekt haben, von dem es Methoden und Eigenschaften erbt und so weiter. Dies wird oft als eine Prototypenkette bezeichnet und erklärt, warum verschiedene Objekte Eigenschaften und Methoden haben, die auf anderen Objekten definiert sind, die ihnen dadurch zur Verfügung stehen.

+ +

Genau gesagt basieren die Eigenschaften und Methoden auf den Prototyp-Eigenschaften der Konstruktorfunktionen der Objekte, nicht auf den Objektinstanzen selbst.

+ +

In JavaScript wird eine Verbindung zwischen der Objektinstanz und ihrem Prototyp hergestellt (seine __proto__-Eigenschaft, die von der Prototyp-Eigenschaft des Konstruktor abgeleitet ist). Die Eigenschaften und Methoden stammen aus der Kette der Prototypen (aufwärts der Prototypenkette folgend).

+ +
+

Hinweis: Es ist wichtig zu wissen, dass es einen Unterschied gibt zwischen dem Prototypen eines Objekts (das über Object.getPrototypeOf(obj) oder über die veraltete __proto__-Eigenschaft zur Verfügung gestellt wird) und der Prototyp-Eigenschaft von Konstruktorfunktionen. Erstere ist die Eigenschaft auf jeder Instanz, letztere ist die Eigenschaft auf dem Konstruktor. Das heißt, Object.getPrototypeOf(new Foobar()) bezieht sich auf dasselbe Objekt wie Foobar.prototype.

+
+ +

Schauen wir uns ein Beispiel an, um dies etwas deutlicher zu machen.

+ +

Verstehen von Prototyp-Objekten

+ +

An dieser Stelle gehen wir zu dem Beispiel zurück, an dem wir unsere Konstruktor-Funktion Person() fertig gestellt haben - bitte laden Sie das Beispiel in Ihrem Browser. Sie können dazu gerne auch unsere Beispieldatei oojs-class-further-exercises.html nutzen (hier finden Sie den Quellcode), falls Ihnen der Quellcode aus dem vorangegangenen Artikel nicht mehr zur Verfügung steht.

+ +

In diesem Beispiel haben wir eine Konstruktorfunktion wie nachfolgend gezeigt definiert:

+ +
function Person(first, last, age, gender, interests) {
+
+  // property and method definitions
+  this.name = {
+    'first': first,
+    'last' : last
+  };
+  this.age = age;
+  this.gender = gender;
+  //...see link in summary above for full definition
+}
+ +

Wir haben dann davon eine Objektinstanz erzeugt, die wie folgt aussieht:

+ +
let person1 = new Person('Bob', 'Smith', 32, 'male', ['music', 'skiing']);
+ +

Wenn Sie in Ihre JavaScript-Konsole person1. eingeben, sollten Sie sehen können, das der Browser versucht, die Ausgabe der in dem Objekt verfügbaren Eigenschaften automatisch zu vervollständigen.

+ +

+ +

In dieser Liste können Sie die Eigenschaften sehen, die in der Konstruktor-Funktion person() definiert sind - name, age, gender, interests, bio und greeting. Sie werden jedoch auch einige andere Eigenschaften sehen können - toString, valueOf etc. - diese sind im Prototyp-Objekt der Konstruktor-Funktion person() definiert.

+ +

+ +

Was passiert eigentlich, wenn man eine Methode auf person1 ausführt, welche aktuell nur im Objekt definiert ist? Zum Beispiel:

+ +
person1.valueOf()
+ +

Die Methode Object.valueOf() wird von person1 geerbt, weil deren Konstruktor-Funktion person() ist und der Prototyp von person() gleich Object() ist. valueOf() gibt den Wert des Objekts zurück, dass die Methode aufruft - probieren Sie es aus und sehen selber! Was in diesem Fall passiert, sieht wie folgt aus:

+ + + +
+

Hinweis: Wir möchten nochmals darauf hinweisen, dass die Methoden und Eigenschaften in der Prototypenkette nicht von einem Objekt auf ein anderes kopiert werden, sondern dass der Zugriff auf sie erfolgt, indem man in der Kette wie oben beschrieben nach oben geht.

+
+ +
+

Hinweis: Es gibt keine offizielle Möglichkeit, direkt auf das Prototyp-Objekt eines Objekts zuzugreifen - die "Links" zwischen den Elementen in der Kette sind in einer internen Eigenschaft definiert, die in der Spezifikation für die JavaScript-Sprache als [[prototype]] bezeichnet wird (siehe {{glossary("ECMAScript")}}). Die meisten modernen Browser verfügen jedoch über eine Eigenschaft namens __proto__ (mit 2 Unterstrichen auf jeder Seite), die das Prototyp-Objekt des Konstruktors des betroffenen Objekts enthält. Geben Sie zum Beispiel person1.__proto__ und person1.__proto__.__proto__ in der JavaScript-Konsole ein, um zu sehen, wie die Kette im Code aussieht!

+ +

Seit ECMAScript 2015 können Sie auf das Prototyp-Objekt eines Objekts indirekt über Object.getPrototypeOf(obj) zugreifen.

+
+ +

Die Prototyp-Eigenschaft: Wo vererbte Mitglieder definiert sind

+ +

Wo sind also die vererbten Eigenschaften und Methoden definiert? Wenn Sie sich die Referenzseite des Konstruktors object ansehen, sehen Sie auf der linken Seite eine große Anzahl von Eigenschaften und Methoden aufgelistet - viel mehr als die Anzahl der geerbten Eigenschaften, die wir auf dem person1-Objekt gesehen haben. Einige werden vererbt, andere nicht - warum ist das so?

+ +

Wie oben erwähnt sind die geerbten diejenigen, die auf der Prototyp-Eigenschaft (man könnte es einen Unter-Namensraum nennen) definiert sind - damit sind die Eigenschaften gemeint, die mit Object.prototype. beginnen und nicht die, die nur mit Object beginnen. Der Wert der Prototyp-Eigenschaft ist ein Objekt, das im Grunde ein Bereich zum Speichern von Eigenschaften und Methoden ist, die wir an Objekte weiter unten in der Prototyp-Kette vererben wollen.

+ +

Somit stehen Object.prototype.toString(), Object.prototype.valueOf() usw. für alle Objekttypen zur Verfügung, die von Object.prototype erben, einschließlich neuer Objektinstanzen, die vom Person()-Konstruktor erstellt werden.

+ +

Object.is(), Object.keys() und andere Eigenschaften, die nicht innerhalb des Prototyp-Bereichs definiert sind, werden nicht von Objektinstanzen oder Objekttypen geerbt, die von Object.prototype erben. Sie sind Methoden/Eigenschaften, die nur auf dem Object()-Konstruktor selbst verfügbar sind.

+ +
+

Hinweis: Das mag ein wenig befremdlich wirken - wie können Sie eine Methode in einem Konstruktor definieren, wenn er selber eine Funktion ist? Eine Funktion ist ebenfalls eine Art Objekt - siehe auch auf der Referenzseite des function()-Konstruktors, damit Sie es besser nachvollziehen können.

+
+ +
    +
  1. Sie können die vorhandenen Prototyp-Eigenschaften selbst überprüfen - gehen Sie zurück zu unserem vorherigen Beispiel und geben Sie folgendes in die JavaScript-Konsole ein: +
    Person.prototype
    +
  2. +
  3. Die Ausgabe wird Ihnen nicht sehr viel zeigen, da wir nichts im Prototyp unseres Custom-Konstruktors definiert haben! Standardmäßig startet der Prototyp eines Konstruktors immer leer. Versuchen Sie jetzt Folgendes: +
    Object.prototype
    +
  4. +
+ +

Sie werden eine große Anzahl von Methoden sehen, die in den Prototyp-Eigenschaften des Objekts (Object) definiert sind, die dann auf Objekten verfügbar sind, die von diesem Objekt (Object) erben, wie bereits gezeigt.

+ +

Sie werden weitere Beispiele für die Vererbung von Prototypenketten sehen, die in JavaScript verfügbar sind - versuchen Sie zum Beispiel, nach den Methoden und Eigenschaften zu suchen, die auf dem Prototyp der globalen Objekte String, Date, Number und Array definiert sind. Diese haben alle eine Anzahl von Elementen, die auf ihrem Prototyp definiert sind, wie z.B. bei der Erstellung einer Zeichenfolge:

+ +
let myString = 'This is my string.';
+ +

myString hat per se eine Reihe nützlicher Methoden zur Verfügung, wie split(), indexOf(), replace() usw.

+ +
+

Hinweis: Es lohnt sich unseren ausführlicheren Leitfaden zur Verwendung von Prototypen in JavaScript zu lesen, sobald Sie diesen Abschnitt verinnerlicht haben und mehr wissen möchten. Dieser Abschnitt ist absichtlich stark vereinfacht, um diese Konzepte bei der ersten Begegnung für Sie etwas leichter verständlich zu machen.

+
+ +
+

Wichtig: Die Prototyp-Eigenschaft ist einer der Teile von JavaScript, die stark verwirrend benannt worden sind - man könnte meinen, dass this auf das Prototyp-Objekt des aktuellen Objekts zeigt, aber das tut sie nicht. prototype ist ein internes Objekt, auf das mit __proto__ zugegriffen werden kann, erinnern Sie sich?

+
+ +

Zurück zu create()

+ +

Etwas früher im Beitrag haben wir gezeigt, wie die Methode Object.create() verwendet werden kann, um eine neue Objektinstanz zu erzeugen.

+ +
    +
  1. Geben Sie folgendes in der JavaScript-Konsole Ihres vorherigen Beispiels ein: +
    let person2 = Object.create(person1);
    +
  2. +
  3. Was create() tatsächlich tut, ist lediglich ein neues Objekt aus einem spezifizierten Prototyp-Objekt zu erstellen. Hier wird person2 erstellt indem person1 als Prototyp Objekt verwendet wird. Man kann das überprüfen indem man das folgende in der Konsole eingibt: +
    person2.__proto__
    +
  4. +
+ +

Dies wird das person1-Objekt zurückgeben.

+ +

Die Konstruktor-Eigenschaft

+ +

Jede Konstruktorfunktion hat eine Prototyp-Eigenschaft, deren Wert ein Objekt ist, das eine constructor-Eigenschaft enthält. Diese Konstruktoreigenschaft zeigt auf die ursprüngliche Konstruktorfunktion. Wie Sie im nächsten Abschnitt sehen werden, werden Eigenschaften, die auf der Person.prototype-Eigenschaft (oder im Allgemeinen auf der Prototyp-Eigenschaft einer Konstruktorfunktion, die ein Objekt ist, wie im obigen Abschnitt erwähnt) definiert sind, für alle Instanzobjekte verfügbar, die mit dem Person()-Konstruktor erstellt werden. Daher ist die Konstruktor-Eigenschaft auch für die beiden Objekte Person1 und Person2 verfügbar.

+ +
    +
  1. Probieren Sie zum Beispiel diese Befehle in der Konsole aus: +
    person1.constructor
    +person2.constructor
    + +

    Diese sollten beide den Person()-Konstruktor zurückgeben, da dieser die ursprüngliche Definition dieser Instanzen enthält.

    + +

    Ein cleverer Trick ist es, dass Sie am Ende der constructor-Eigenschaft Klammern setzen können (die alle erforderlichen Parameter enthalten), um eine weitere Objektinstanz aus diesem Konstruktor zu erzeugen. Der Konstruktor ist schließlich eine Funktion und kann daher mit Hilfe von Klammern aufgerufen werden; Sie müssen nur das neue Schlüsselwort einfügen, um anzugeben, dass Sie die Funktion als Konstruktor verwenden wollen.

    +
  2. +
  3. Geben Sie folgendes in die Konsole ein: +
    let person3 = new person1.constructor('Karen', 'Stephenson', 26, 'female', ['playing drums', 'mountain climbing']);
    +
  4. +
  5. Nun können Sie zum Beispiel auf die Funktionen Ihres neuen Objekts zuzugreifen: +
    person3.name.first
    +person3.age
    +person3.bio()
    +
  6. +
+ +

Das funktioniert gut. Sie werden es nicht oft benutzen müssen, aber es kann wirklich nützlich sein, wenn Sie eine neue Instanz erzeugen wollen und aus irgendeinem Grund keine Referenz auf den Originalkonstruktor leicht verfügbar ist.

+ +

Die constructor-Eigenschaft hat andere Verwendungsmöglichkeiten. Wenn Sie z.B. eine Objektinstanz haben und den Namen des Konstruktors zurückgeben wollen, von dem das Objekt eine Instanz ist, können Sie Folgendes verwenden:

+ +
instanceName.constructor.name
+ +

Geben Sie zum Beispiel folgendes ein:

+ +
person1.constructor.name
+
+ +
+

Hinweis: Der Wert von constructor.name kann sich ändern (aufgrund von prototypischer Vererbung, Bindung, Präprozessoren, Transpilern, etc.), so dass Sie für komplexere Beispiele stattdessen den instanceof-Operator verwenden sollten.

+
+ +
    +
+ +

Prototypen modifizieren

+ +

Schauen wir uns ein Beispiel für die Veränderung der Prototyp-Eigenschaft einer Konstruktor-Funktion näher an - Methoden, die dem Prototyp hinzugefügt werden, sind dann auf allen Objektinstanzen verfügbar, die aus dem Konstruktor heraus erzeugt werden. An diesem Punkt werden wir schließlich etwas zum Prototyp unseres Konstruktors Person() hinzufügen.

+ +
    +
  1. Gehen Sie zurück zu unserem Beispiel oojs-class-further-exercises.html und erstellen Sie eine lokale Kopie des Quellcodes. Fügen Sie unter dem vorhandenen JavaScript den folgenden Code hinzu, der eine neue Methode zur Prototyp-Eigenschaft des Konstruktors hinzufügt: + +
    Person.prototype.farewell = function() {
    +  alert(this.name.first + ' has left the building. Bye for now!');
    +};
    +
  2. +
  3. Speichern Sie bitte den Code, laden den Browser neu und geben bitte folgendes in die Konsole ein: +
    person1.farewell();
    +
  4. +
+ +

Sie sollten eine Warnmeldung erhalten, die den Namen der Person, wie er im Konstruktor definiert ist, anzeigt. Das ist wirklich nützlich, aber noch nützlicher ist, dass die gesamte Vererbungskette dynamisch aktualisiert wurde, wodurch diese neue Methode automatisch auf allen vom Konstruktor abgeleiteten Objektinstanzen verfügbar ist.

+ +

Denken Sie einen Moment in Ruhe darüber nach. In unserem Code definieren wir den Konstruktor, dann erzeugen wir ein Instanzobjekt aus dem Konstruktor, dann fügen wir dem Prototypen des Konstruktors eine neue Methode hinzu:

+ +
function Person(first, last, age, gender, interests) {
+
+  // Definition der Eigenschaften und methoden
+
+}
+
+let person1 = new Person('Tammi', 'Smith', 32, 'neutral', ['music', 'skiing', 'kickboxing']);
+
+Person.prototype.farewell = function() {
+  alert(this.name.first + ' has left the building. Bye for now!');
+};
+ +

Aber die Methode farewell() ist immer noch auf der person1-Objektinstanz verfügbar - ihre Mitglieder wurden automatisch aktualisiert, um die neu definierte Methode farewell() aufzunehmen.

+ +
+

Hinweis: Sie können dazu gerne auch unsere Beispieldatei oojs-class-further-exercises.html nutzen (hier finden Sie den Quellcode), falls Ihnen der Quellcode aus dem vorangegangenen Artikel nicht mehr zur Verfügung steht bzw. Ihr Quellcode nicht funktioniert.

+
+ +

Sie werden nur selten Eigenschaften sehen, die auf der Prototyp-Eigenschaft definiert sind, weil sie nicht sehr flexibel sind, wenn sie so definiert worden. Sie könnten zum Beispiel eine solche Eigenschaft hinzufügen:

+ +
Person.prototype.fullName = 'Bob Smith';
+ +

Das ist nicht sehr flexibel, da die Person vielleicht nicht so genannt wird. Es wäre viel besser, den vollen Namen aus name.first und name.last zu bilden:

+ +
Person.prototype.fullName = this.name.first + ' ' + this.name.last;
+ +

Dies funktioniert jedoch nicht, da sich this in diesem Fall auf den globalen Bereich bezieht, nicht auf den Funktionsbereich. Der Aufruf dieser Eigenschaft würde undefined zurückgeben. Dies funktionierte gut auf die Methode, die wir früher im Prototyp definiert haben, weil sie innerhalb eines Funktionsbereichs sitzt, der erfolgreich in den Objektinstanzbereich übertragen wird. Sie können also konstante Eigenschaften auf dem Prototyp definieren (d.h. solche, die sich nie ändern müssen), aber im allgemeinen funktioniert es besser, Eigenschaften innerhalb des Konstruktors zu definieren.

+ +

In der Tat ist es üblich, für weitere Objektdefinitionen die Eigenschaften innerhalb des Konstruktors und die Methoden auf dem Prototyp zu definieren. Dies macht den Code leichter lesbar, da der Konstruktor nur die Eigenschaftsdefinitionen enthält und die Methoden in separate Blöcke aufgeteilt sind. Zum Beispiel:

+ +
// Konstruktor mit der Definition der Eigenschaften
+
+function Test(a, b, c, d) {
+  // property definitions
+}
+
+// eine erste Methode wird definiert
+
+Test.prototype.x = function() { ... };
+
+// eine zweite Methode wird definiert
+
+Test.prototype.y = function() { ... };
+
+// etc.
+ +

Dieses Muster kann in Aktion im Beispiel der Schulplan-App von Piotr Zalewa gesehen werden.

+ +

Zusammenfassung

+ +


+ Dieser Beitrag hat Objekt-Prototypen in JavaScript behandelt, einschließlich wie Prototyp-Objektketten es ermöglichen, das Objekte voneinander Funktionen (ver)erben können, sowie Prototyp-Eigenschaften und wie diese verwendet werden können, um neue Methoden zu Konstruktoren hinzuzufügen. Darüber hinaus andere mit den Themen verwandte Themen.

+ +

Im nächsten Artikel sehen wir uns an, wie Sie die Vererbung von Funktionalität zwischen zwei Ihrer eigenen benutzerdefinierten Objekte implementieren können.

+ +

{{PreviousMenuNext("Learn/JavaScript/Objects/Object-oriented_JS", "Learn/JavaScript/Objects/Inheritance", "Learn/JavaScript/Objects")}}

+ +

In diesem Modul

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