From 8f2731905212f6e7eb2d9793ad20b8b448c54ccf Mon Sep 17 00:00:00 2001 From: Florian Merz Date: Thu, 11 Feb 2021 14:51:31 +0100 Subject: unslug tr: move --- .../first_steps/a_first_splash/index.html | 600 +++++++++++++++++++++ files/tr/learn/javascript/first_steps/index.html | 61 +++ files/tr/learn/javascript/index.html | 56 ++ .../tr/learn/javascript/objects/basics/index.html | 257 +++++++++ files/tr/learn/javascript/objects/index.html | 53 ++ 5 files changed, 1027 insertions(+) create mode 100644 files/tr/learn/javascript/first_steps/a_first_splash/index.html create mode 100644 files/tr/learn/javascript/first_steps/index.html create mode 100644 files/tr/learn/javascript/index.html create mode 100644 files/tr/learn/javascript/objects/basics/index.html create mode 100644 files/tr/learn/javascript/objects/index.html (limited to 'files/tr/learn/javascript') diff --git a/files/tr/learn/javascript/first_steps/a_first_splash/index.html b/files/tr/learn/javascript/first_steps/a_first_splash/index.html new file mode 100644 index 0000000000..8cab0bbcf2 --- /dev/null +++ b/files/tr/learn/javascript/first_steps/a_first_splash/index.html @@ -0,0 +1,600 @@ +--- +title: Javascript'e ilk giriş +slug: Öğren/JavaScript/First_steps/Javascripte_giris +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")}}
+ +

Artık JavaScript teorisi ve onunla neler yapabileceğiniz hakkında bir şeyler öğrendiniz, tamamen pratik bir öğretici aracılığıyla size JavaScript'in temel özellikleri hakkında hızlandırılmış bir kurs vereceğiz. Burada adım adım basit bir "Sayıyı tahmin et" oyunu oluşturacaksınız.

+ + + + + + + + + + + + +
Prerequisites:Basic computer literacy, a basic understanding of HTML and CSS, an understanding of what JavaScript is.
Objective:To have a first bit of experience at writing some JavaScript, and gain at least a basic understanding of what writing a JavaScript program involves.
+ +

You won't be expected to understand all of the code in detail immediately — we just want to introduce you to the high-level concepts for now, and give you an idea of how JavaScript (and other programming languages) work. In subsequent articles, you'll revisit all these features in a lot more detail!

+ +
+

Note: Many of the code features you'll see in JavaScript are the same as in other programming languages — functions, loops, etc. The code syntax looks different, but the concepts are still largely the same.

+
+ +

Thinking like a programmer

+ +

One of the hardest things to learn in programming is not the syntax you need to learn, but how to apply it to solve real world problems. You need to start thinking like a programmer — this generally involves looking at descriptions of what your program needs to do, working out what code features are needed to achieve those things, and how to make them work together.

+ +

This requires a mixture of hard work, experience with the programming syntax, and practice — plus a bit of creativity. The more you code, the better you'll get at it. We can't promise that you'll develop "programmer brain" in five minutes, but we will give you plenty of opportunity to practice thinking like a programmer throughout the course.

+ +

With that in mind, let's look at the example we'll be building up in this article, and review the general process of dissecting it into tangible tasks.

+ +

Example — Guess the number game

+ +

In this article we'll show you how to build up the simple game you can see below:

+ + + +

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

+ +

Have a go at playing it — familiarize yourself with the game before you move on.

+ +

Let's imagine your boss has given you the following brief for creating this game:

+ +
+

I want you to create a simple guess the number type game. It should choose a random number between 1 and 100, then challenge the player to guess the number in 10 turns. After each turn the player should be told if they are right or wrong, and if they are wrong, whether the guess was too low or too high. It should also tell the player what numbers they previously guessed. The game will end once the player guesses correctly, or once they run out of turns. When the game ends, the player should be given an option to start playing again.

+
+ +

Upon looking at this brief, the first thing we can do is to start breaking it down into simple actionable tasks, in as much of a programmer mindset as possible:

+ +
    +
  1. Generate a random number between 1 and 100.
  2. +
  3. Record the turn number the player is on. Start it on 1.
  4. +
  5. Provide the player with a way to guess what the number is.
  6. +
  7. Once a guess has been submitted first record it somewhere so the user can see their previous guesses.
  8. +
  9. Next, check whether it is the correct number.
  10. +
  11. If it is correct: +
      +
    1. Display congratulations message.
    2. +
    3. Stop the player from being able to enter more guesses (this would mess the game up).
    4. +
    5. Display control allowing the player to restart the game.
    6. +
    +
  12. +
  13. If it is wrong and the player has turns left: +
      +
    1. Tell the player they are wrong.
    2. +
    3. Allow them to enter another guess.
    4. +
    5. Increment the turn number by 1.
    6. +
    +
  14. +
  15. If it is wrong and the player has no turns left: +
      +
    1. Tell the player it is game over.
    2. +
    3. Stop the player from being able to enter more guesses (this would mess the game up).
    4. +
    5. Display control allowing the player to restart the game.
    6. +
    +
  16. +
  17. Once the game restarts, make sure the game logic and UI are completely reset, then go back to step 1.
  18. +
+ +

Let's now move forward, looking at how we can turn these steps into code, building up the example, and exploring JavaScript features as we go.

+ +

Initial setup

+ +

To begin this tutorial, we'd like you to make a local copy of the number-guessing-game-start.html file (see it live here). Open it in both your text editor and your web browser. At the moment you'll see a simple heading, paragraph of instructions and form for entering a guess, but the form won't currently do anything.

+ +

The place where we'll be adding all our code is inside the {{htmlelement("script")}} element at the bottom of the HTML:

+ +
<script>
+
+  // Your JavaScript goes here
+
+</script>
+
+ +

Adding variables to store our data

+ +

Let's get started. First of all, add the following lines inside your {{htmlelement("script")}} element:

+ +
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;
+ +

This section of the code sets up the variables and constants we need to store the data our program will use. Variables are basically containers for values (such as numbers, or strings of text). You create a variable with the keyword let (or var) followed by a name for your variable (you'll read more about the difference between the keywords in a future article). Constants are used to store values that are immutable or can't be changed and are created with the keyword const. In this case, we are using constants to store references to parts of our user interface; the text inside some of them might change, but the HTML elements referenced stay the same.

+ +

You can assign a value to your variable or constant with an equals sign (=) followed by the value you want to give it.

+ +

In our example:

+ + + +
+

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 math, 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.append(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. A 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:

+ +
const 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, most of the items you will manipulate in your code are objects. 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 now has 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 guessField into the console and the console shows 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 guesses into the console and pressing return. The console shows you that the variable contains a {{htmlelement("p")}} element.
  10. +
  11. Now try entering the following line: +
    guesses.value
    + The browser returns 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/tr/learn/javascript/first_steps/index.html b/files/tr/learn/javascript/first_steps/index.html new file mode 100644 index 0000000000..cde2569c69 --- /dev/null +++ b/files/tr/learn/javascript/first_steps/index.html @@ -0,0 +1,61 @@ +--- +title: JavaScript First Steps +slug: Öğren/JavaScript/First_steps +tags: + - türkçe +translation_of: Learn/JavaScript/First_steps +--- +
{{LearnSidebar}}
+ +

In our first JavaScript module, we first answer some fundamental questions such as "what is JavaScript?", "what does it look like?", and "what can it do?", before moving on to taking you through your first practical experience of writing JavaScript. After that, we discuss some key building blocks in detail, such as variables, strings, numbers and arrays.

+ +

Prerequisites

+ +

Before starting this module, you don't need any previous JavaScript knowledge, but you should have some familiarity with HTML and CSS. You are advised to work through the following modules before starting on JavaScript:

+ + + +
+

Note: If you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as JSBin or Glitch.

+
+ +

Guides

+ +
+
What is JavaScript?
+
Welcome to the MDN beginner's JavaScript course! In this first article we will look at JavaScript from a high level, answering questions such as "what is it?", and "what is it doing?", and making sure you are comfortable with JavaScript's purpose.
+
A first splash into JavaScript
+
Now you've learned something about the theory of JavaScript, and what you can do with it, we are going to give you a crash course in the basic features of JavaScript via a completely practical tutorial. Here you'll build up a simple "Guess the number" game, step by step.
+
What went wrong? Troubleshooting JavaScript
+
When you built up the "Guess the number" game in the previous article, you may have found that it didn't work. Never fear — this article aims to save you from tearing your hair out over such problems by providing you with some simple tips on how to find and fix errors in JavaScript programs.
+
Storing the information you need — Variables
+
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.
+
Basic math in JavaScript — numbers and operators
+
At this point in the course we discuss maths in JavaScript — how we can combine operators and other features to successfully manipulate numbers to do our bidding.
+
Handling text — strings in JavaScript
+
Next we'll turn our attention to strings — this is what pieces of text are called in programming. In this article we'll look at all the common things that you really ought to know about strings when learning JavaScript, such as creating strings, escaping quotes in string, and joining them together.
+
Useful string methods
+
Now we've looked at the very basics of strings, let's move up a gear and start thinking about what useful operations we can do on strings with built-in methods, such as finding the length of a text string, joining and splitting strings, substituting one character in a string for another, and more.
+
Arrays
+
In the final article of this module, we'll look at arrays — a neat way of storing a list of data items under a single variable name. Here we look at why this is useful, then explore how to create an array, retrieve, add, and remove items stored in an array, and more besides.
+
+ +

Assessments

+ +

The following assessment will test your understanding of the JavaScript basics covered in the guides above.

+ +
+
Silly story generator
+
In this assessment you'll be tasked with taking some of the knowledge you've picked up in this module's articles and applying it to creating a fun app that generates random silly stories. Have fun!
+
+ +

See also

+ +
+
Learn JavaScript
+
An excellent resource for aspiring web developers — Learn JavaScript in an interactive environment, with short lessons and interactive tests, guided by automated assessment. The first 40 lessons are free, and the complete course is available for a small one-time payment.
+
diff --git a/files/tr/learn/javascript/index.html b/files/tr/learn/javascript/index.html new file mode 100644 index 0000000000..665e95cc85 --- /dev/null +++ b/files/tr/learn/javascript/index.html @@ -0,0 +1,56 @@ +--- +title: JavaScript +slug: Öğren/JavaScript +translation_of: Learn/JavaScript +--- +
{{LearnSidebar}}
+ +

{{Glossary("JavaScript")}} web sayfalarında karmaşık şeyler yapmanıza olanak sağlayan bir programlama dilidir. Ne zaman bir web sayfası ekranınızda sabit durup ve size sabit bilgiler sunmanın fazlasını yaptığında, zaman zaman size içerik güncellemeleri, ya da etkileşilimli haritalar, ya da animasyonlu iki ve üç boyutlu grafikler, ya da kayan video müzik kutuları vs. gösterdiğinde, JavaScript'in muhtemelen bu işe dahil olduğundan emin olabilirsiniz.

+ +

Öğrenme yolu

+ +

JavaScript'i öğrenmek ilgili teknolojiler olan HTML ve CSS'e kıyasla daha zor olabilir. JavaScript'i öğrenmeye başlamadan önce, bu iki teknolojiye ve belki diğer benzer teknolojilere aşina olmanız şiddetle önerilir. Aşağıdaki modüllerle işe başlayabilirsiniz:

+ + + +

Ayrıca diğer programlama dilleriyle önceden edindiğiniz tecrübelerin size yardımı dokunacaktır.

+ +

JavaScript'in temellerine aşina olduktan sonra, daha ileri seviyedeki konuları öğrenmeye başlayabilirsiniz, örneğin:

+ + + +

Modüller

+ +

Bu konu, önerilen çalışma sırasıyla, aşağıdaki modülleri içerir.

+ +
+
JavaScript ilk adımlar
+
İlk JavaScript modülümüzde, sizi ilk JavaScript yazma tecrübesine götürmedeen önce, ilk olarak "JavaScript nedir?", "Neye benzer?", ve "Neler yapabilir?" gibi temel sorulara cevap veriyoruz. Daha sonra, değişkenler, harf dizileri, sayılar ve diziler gibi temel JavaScript özelliklerini detaylı bir şekilde tartışıyoruz.
+
JavaScript yapı taşları
+
Bu modülde, JavaScript'in tüm temel özelliklerini ele almaya devam ederek dikkatimizi koşullu ifadeler, döngüler, işlevler ve olaylar gibi sık karşılaşılan kod bloğu türlerine çeviriyoruz. Bunları zaten kursta gördünüz, ancak yalnızca yüzeysel - burada hepsini açıkça tartışacağız.
+
JavaScript nesnelerine giriş
+
JavaScript'te, dizeler ve diziler gibi temel JavaScript özelliklerinden, JavaScript üzerine oluşturulan tarayıcı API'lerine kadar çoğu şey nesnelerdir. İlgili işlevleri ve değişkenleri verimli paketler halinde kapsüllemek için kendi nesnelerinizi bile oluşturabilirsiniz. Dil bilginizle daha ileri gitmek ve daha verimli kod yazmak istiyorsanız JavaScript'in nesne yönelimli doğasını anlamak önemlidir, bu nedenle size yardımcı olmak için bu modülü sağladık. Burada nesne teorisini ve sözdizimini ayrıntılı olarak öğretiyor, kendi nesnelerinizi nasıl yaratacağınıza bakıyoruz ve JSON verilerinin ne olduğunu ve onunla nasıl çalışılacağını açıklıyoruz.
+
Asenkron JavaScript
+
+

Bu modülde asenkron JavaScript'e, bunun neden önemli olduğuna ve bir sunucudan kaynakların alınması gibi olası engelleme işlemlerini etkili bir şekilde idare etmek için nasıl kullanılabileceğine bir göz atacağız.

+
+
+
İstemci tarafı web API'leri
+
When writing client-side JavaScript for web sites or applications, you won't go very far before you start to use APIs — interfaces for manipulating different aspects of the browser and operating system the site is running on, or even data from other web sites or services. In this module we will explore what APIs are, and how to use some of the most common APIs you'll come across often in your development work.
+
+ +

See also

+ +
+
JavaScript on MDN
+
The main entry point for core JavaScript documentation on MDN — this is where you'll find extensive reference docs on all aspects of the JavaScript language, and some advanced tutorials aimed at experienced JavaScripters.
+
Coding math
+
An excellent series of video tutorials to teach the math you need to understand to be an effective programmer, by Keith Peters.
+
diff --git a/files/tr/learn/javascript/objects/basics/index.html b/files/tr/learn/javascript/objects/basics/index.html new file mode 100644 index 0000000000..bf6e7892e0 --- /dev/null +++ b/files/tr/learn/javascript/objects/basics/index.html @@ -0,0 +1,257 @@ +--- +title: JavaScript object basics +slug: Öğren/JavaScript/Objeler/Basics +translation_of: Learn/JavaScript/Objects/Basics +--- +
{{LearnSidebar}}
+ +
{{NextMenu("Learn/JavaScript/Objects/Object-oriented_JS", "Learn/JavaScript/Objects")}}
+ +

Bu makalede JavaScript'in nesne sözdizim kurallarını inceleyeceğiz ve daha önceden gördüğümüz diğer özellikleri ziyaret edip bu işlevlerin aslında bir nesne olduğunu tekrar edeceğiz.

+ + + + + + + + + + + + +
Gereksinimler:Temel bilgisayar okuryazarlığı, temel HMTL ve CSS bilgisi ve JavaScript temelleri (İlk adımlar ve yapı taşları)
Amaç:Nesneye yönelik programlama ile ilgili temel teoriyi anlamak ve bunun JavaScript'teki ("Javascript'te birçok şey nesnedir") sözü ile ilişkisini keşfetmek ve JavaScript nesneleri ile çalışmak.
+ +

Nesne temelleri

+ +

Bir nesne birtakım ilişkili veri ve/veya fonksiyonalite (genellikle birden fazla değişken ve fonksiyondan oluşur — ve bunlar nesne içerisinde olduklarında nesnenin niteliği (property) ve fonksiyonları adını alırlar.) Bir örnek üzerinde çalışarak nasıl olduklarını anlayalım.

+ +

Başlamak için oojs.html dosyasını kopyalayın. Bu dosya çok küçük bir içeriğe sahip —  bir {{HTMLElement("script")}} elementi içine kaynak kodumuzu yazacağız. Bunu temel nesne sözdizimini anlamak için baz alacağız. Bu örnek üzerinde çalışırken geliştirici JavaScript konsolunu açık ve komutları yazmaya hazır şekilde tutun.

+ +

Nesne oluşturmak, Javascript'te bir çok konuda olduğu gibi bir değişken tanımlamak ile başlar.  Aşağıdaki Javascript kodunu dosyasına kopyalayarak dosyayı kaydedin ve tarayıcınızı yenileyin.

+ +
const person = {};
+ +

Şimdi tarayıcınızın JavaScript konsolunu açın, person yazın, ve Enter/Return tuşlarına basın. Aşağıdaki satırlara benzer açıklamalar ile karşılaşacaksınız. 

+ +
[object Object]
+Object { }
+{ }
+
+ +

Congratulations, you've just created your first object. Job done! But this is an empty object, so we can't really do much with it. Let's update the JavaScript object in our file to look like this:

+ +
const 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] + '.');
+  }
+};
+
+ +

After saving and refreshing, try entering some of the following into the JavaScript console on your browser devtools:

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

You have now got some data and functionality inside your object, and are now able to access them with some nice simple syntax!

+ +
+

Note: If you are having trouble getting this to work, try comparing your code against our version — see oojs-finished.html (also see it running live). The live version will give you a blank screen, but that's OK — again, open your devtools and try typing in the above commands to see the object structure.

+
+ +

So what is going on here? Well, an object is made up of multiple members, each of which has a name (e.g. name and age above), and a value (e.g. ['Bob', 'Smith'] and 32). Each name/value pair must be separated by a comma, and the name and value in each case are separated by a colon. The syntax always follows this pattern:

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

The value of an object member can be pretty much anything — in our person object we've got a string, a number, two arrays, and two functions. The first four items are data items, and are referred to as the object's properties. The last two items are functions that allow the object to do something with that data, and are referred to as the object's methods.

+ +

An object like this is referred to as an object literal — we've literally written out the object contents as we've come to create it. This is in contrast to objects instantiated from classes, which we'll look at later on.

+ +

It is very common to create an object using an object literal when you want to transfer a series of structured, related data items in some manner, for example sending a request to the server to be put into a database. Sending a single object is much more efficient than sending several items individually, and it is easier to work with than an array, when you want to identify individual items by name.

+ +

Dot notation

+ +

Above, you accessed the object's properties and methods using dot notation. The object name (person) acts as the namespace — it must be entered first to access anything encapsulated inside the object. Next you write a dot, then the item you want to access — this can be the name of a simple property, an item of an array property, or a call to one of the object's methods, for example:

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

Sub-namespaces

+ +

It is even possible to make the value of an object member another object. For example, try changing the name member from

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

to

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

Here we are effectively creating a sub-namespace. This sounds complex, but really it's not — to access these items you just need to chain the extra step onto the end with another dot. Try these in the JS console:

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

Important: At this point you'll also need to go through your method code and change any instances of

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

to

+ +
name.first
+name.last
+ +

Otherwise your methods will no longer work.

+ +

Bracket notation

+ +

There is another way to access object properties — using bracket notation. Instead of using these:

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

You can use

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

This looks very similar to how you access the items in an array, and it is basically the same thing — instead of using an index number to select an item, you are using the name associated with each member's value. It is no wonder that objects are sometimes called associative arrays — they map strings to values in the same way that arrays map numbers to values.

+ +

Setting object members

+ +

So far we've only looked at retrieving (or getting) object members — you can also set (update) the value of object members by simply declaring the member you want to set (using dot or bracket notation), like this:

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

Try entering the above lines, and then getting the members again to see how they've changed, like so:

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

Setting members doesn't just stop at updating the values of existing properties and methods; you can also create completely new members. Try these in the JS console:

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

You can now test out your new members:

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

One useful aspect of bracket notation is that it can be used to set not only member values dynamically, but member names too. Let's say we wanted users to be able to store custom value types in their people data, by typing the member name and value into two text inputs. We could get those values like this:

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

We could then add this new member name and value to the person object like this:

+ +
person[myDataName] = myDataValue;
+ +

To test this, try adding the following lines into your code, just below the closing curly brace of the person object:

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

Now try saving and refreshing, and entering the following into your text input:

+ +
person.height
+ +

Adding a property to an object using the method above isn't possible with dot notation, which can only accept a literal member name, not a variable value pointing to a name.

+ +

What is "this"?

+ +

You may have noticed something slightly strange in our methods. Look at this one for example:

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

You are probably wondering what "this" is. The this keyword refers to the current object the code is being written inside — so in this case this is equivalent to person. So why not just write person instead? As you'll see in the Object-oriented JavaScript for beginners article, when we start creating constructors and so on, this is very useful — it always ensures that the correct values are used when a member's context changes (for example, two different person object instances may have different names, but we want to use their own name when saying their greeting).

+ +

Let's illustrate what we mean with a simplified pair of person objects:

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

In this case, person1.greeting() outputs "Hi! I'm Chris."; person2.greeting() on the other hand outputs "Hi! I'm Deepti.", even though the method's code is exactly the same in each case. As we said earlier, this is equal to the object the code is inside — this isn't hugely useful when you are writing out object literals by hand, but it really comes into its own when you are dynamically generating objects (for example using constructors). It will all become clearer later on.

+ +

You've been using objects all along

+ +

As you've been going through these examples, you have probably been thinking that the dot notation you've been using is very familiar. That's because you've been using it throughout the course! Every time we've been working through an example that uses a built-in browser API or JavaScript object, we've been using objects, because such features are built using exactly the same kind of object structures that we've been looking at here, albeit more complex ones than in our own basic custom examples.

+ +

So when you used string methods like:

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

You were using a method available on an instance of the String class. Every time you create a string in your code, that string is automatically created as an instance of String, and therefore has several common methods and properties available on it.

+ +

When you accessed the document object model using lines like this:

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

You were using methods available on an instance of the Document class. For each webpage loaded, an instance of Document is created, called document, which represents the entire page's structure, content, and other features such as its URL. Again, this means that it has several common methods and properties available on it.

+ +

The same is true of pretty much any other built-in object or API you've been using — Array, Math, and so on.

+ +

Note that built in objects and APIs don't always create object instances automatically. As an example, the Notifications API — which allows modern browsers to fire system notifications — requires you to instantiate a new object instance using the constructor for each notification you want to fire. Try entering the following into your JavaScript console:

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

Again, we'll look at constructors in a later article.

+ +
+

Note: It is useful to think about the way objects communicate as message passing — when an object needs another object to perform some kind of action often it sends a message to another object via one of its methods, and waits for a response, which we know as a return value.

+
+ +

Summary

+ +

Congratulations, you've reached the end of our first JS objects article — you should now have a good idea of how to work with objects in JavaScript — including creating your own simple objects. You should also appreciate that objects are very useful as structures for storing related data and functionality — if you tried to keep track of all the properties and methods in our person object as separate variables and functions, it would be inefficient and frustrating, and we'd run the risk of clashing with other variables and functions that have the same names. Objects let us keep the information safely locked away in their own package, out of harm's way.

+ +

In the next article we'll start to look at object-oriented programming (OOP) theory, and how such techniques can be used in JavaScript.

+ +

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

+ +

In this module

+ + diff --git a/files/tr/learn/javascript/objects/index.html b/files/tr/learn/javascript/objects/index.html new file mode 100644 index 0000000000..d90a7e81a4 --- /dev/null +++ b/files/tr/learn/javascript/objects/index.html @@ -0,0 +1,53 @@ +--- +title: Javascript Nesnelerine Giriş +slug: Öğren/JavaScript/Objeler +tags: + - Başlangıç + - Değerlendirme + - JavaScript + - Kılavuz + - Makale + - Nesneler + - Objeler + - Rehber + - Yeni başlayan + - öğren +translation_of: Learn/JavaScript/Objects +--- +
{{LearnSidebar}}
+ +

JavaScript'te, JavaScript'in esas özelliklerinden olan karakter katarları ve dizilerden JavaScript'in tepesine inşa edilmiş tarayıcı uygulama geliştirme arayüzlerine ({{Glossary("API", "API")}}) kadar çoğu şey nesnedir. Kendi nesnelerinizi oluşturarak alakalı değişkenleri ve fonksiyonları etkili paketlere kapsülleyebilir ve onlara yararlı veri paketleri gibi davranabilirsiniz. JavaScript'in nesneye dayalı doğası dildeki bilgi birikiminizi arttırmak istiyorsanız önemlidir, bundan dolayı bu modülü size yardım etmek için temin ettik. Burda nesne teorisini ve sözdizimini detaylarıyla öğretiyoruz, sonra kendi nesnelerinizi nasıl oluşturacağınıza bakıyoruz.

+ +

Ön Koşullar

+ +

Bu konuya başlamadan önce HTML ve CSS'ye aşina olmalısınız.  Javascript'e başlamadan önce Introduction to HTML ve Introduction to CSS konularına çalışmanız önerilir.

+ +

Javascript nesnelerine ayrıntılı olarak bakmadan önce Javascript Temelleri hakkında da bilgi sahibi olmalısınız. Bu konudan önce JavaScript first steps ve JavaScript building blocks konularına bakın.

+ +
+

Not: Eğer kendi dosyalarınızı oluşturma özelliği olmayan bir bilgisayar/tablet/diğer cihazda çalışıyorsanız JSBin veya Thimble gibi çoğu kod örneğini deneyebileceğiniz online kodlama programlarını deneyebilirsiniz.

+
+ +

Rehberler

+ +
+
Nesne Temelleri
+
İlk makalede JavaScript nesnelerine, JavaScript nesne sözdizimi temellerine bakacağız ve kursun başlarında baktığımız bazı JavaScript özelliklerine uğraştığınız birçok özelliğin aslında nesne olduğunu tekrar tekrar hatırlatarak göz atacağız.
+
Yeni başlayanlar için nesneye dayalı JavaScript
+
Temeller yolumuzdan çekildiğine göre nesneye dayalı JavaScript'e (OOJS) odaklanabiliriz— bu makale nesneye dayalı programlama teorisinin temelini basitçe tanıtır sonra JavaScript'in yapıcı fonksiyonlarla nesne sınıflarını nasıl taklit ettiğini ve nasıl nesne örnekleri yarattığını araştırır.
+
Nesne prototipleri
+
Prototipler JavaScript nesnelerinin birbirinden özellik kalıtım almasının mekanizmasıdır ve diğer nesneye dayalı programlama dillerinden farklı çalışırlar.Bu makalede bu farkı keşfedeceğiz, prototip zincirlerinin nasıl çalıştığını açıklayacağız ve halihazırda var olan yapıcılara prototip özelliğini kullanarak nasıl metod eklenebileceğine göz atacağız.
+
JavaScript'te kalıtım
+
OOJS'nin neredeyse tüm korkutucu detayları açıklanmış oldu bu makale size "ebeveyn" sınıftan özellikleri kalıtım alan "çocuk" nesne sınıflarını (yapıcılar) nasıl oluşturacağınızı gösterecek.
+
JSON verileri ile çalışmak
+
JavaScript Nesne Notasyonu web sitelerinde veriyi taşımak ve temsil etmek (yani web sayfasının kullanıcıda görüntülenebilmesi için serverdan veri göndermek) için sıkça kullanılan JavaScript nesne sözdizimine dayalı yapısal veriyi temsil etmek için kullanılan metin tabanlı bir standart biçimdir.  Bununla sıkça karşılaşacağınız için bu makalede JavaScript kullanarak JSON ile çalışmanız ve kendi JSON'unuzu yazmanız için gerekli olan JSON ayrıştırması dahil her şeyi size verdik.
+
Nesne inşa etme uygulaması
+
Önceki makalelerde sağlam temeller üzerinden gitmek için gerekli olan JavaScript nesne teorisini ve sözdizim örneklerine baktık. Bu makalede ise eğlenceli ve renkli bir şey ortaya çıkarmanızı sağlayacak özel JavaScript nesnelerini inşa etmenize olanak sağlayacak bir uygulama yapacağız.
+
+ +

Değerlendirmeler

+ +
+
Zıplayan toplar demosuna özellikler ekleme
+
Bu değerlendirmede sizden, önceki makaledeki zıplayan toplar demosunu başlangıç noktası olarak almak ve ona ilginç özellikler eklemeniz bekleniyor.
+
-- cgit v1.2.3-54-g00ecf