aboutsummaryrefslogtreecommitdiff
path: root/files/uk/learn/javascript/objects/object-oriented_js/index.html
diff options
context:
space:
mode:
Diffstat (limited to 'files/uk/learn/javascript/objects/object-oriented_js/index.html')
-rw-r--r--files/uk/learn/javascript/objects/object-oriented_js/index.html295
1 files changed, 295 insertions, 0 deletions
diff --git a/files/uk/learn/javascript/objects/object-oriented_js/index.html b/files/uk/learn/javascript/objects/object-oriented_js/index.html
new file mode 100644
index 0000000000..67b61867ff
--- /dev/null
+++ b/files/uk/learn/javascript/objects/object-oriented_js/index.html
@@ -0,0 +1,295 @@
+---
+title: Об'єктно-орієнтований JavaScript для початківців
+slug: Learn/JavaScript/Objects/Object-oriented_JS
+translation_of: Learn/JavaScript/Objects/Object-oriented_JS
+---
+<div>{{LearnSidebar}}</div>
+
+<div>{{PreviousMenuNext("Learn/JavaScript/Objects/Basics", "Learn/JavaScript/Objects/Object_prototypes", "Learn/JavaScript/Objects")}}</div>
+
+<p class="summary">Розібравшись з основами, зосередимось на об'єктно-орієнтованому JavaScript (OOJS) - в цій статті представлені основні позиції теорії об'єктно-орієнтованого програмування (ООП) , потім розглянемо, як в JavaScript емулювати класи об'єктів за допомогою функції конструктора, і як створити екземпляри об'єктів.</p>
+
+<table class="learn-box standard-table">
+ <tbody>
+ <tr>
+ <th scope="row">
+ <table>
+ <tbody>
+ <tr>
+ <th scope="row">Необхідні знання:</th>
+ <td>Елементарна комп'ютерна грамотність, базове розуміння HTML та CSS, знайомство з основами JavaScript (див. <a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps">First steps</a> та <a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks">Building blocks</a>) і основи OOJS (див. <a href="https://developer.mozilla.org/uk/docs/Learn/JavaScript/Objects/Basics">Основи об'єктів в JS</a>).</td>
+ </tr>
+ <tr>
+ <th scope="row">Мета:</th>
+ <td>Розуміння основ теоріі об'єктно-орієнтованого програмування, як це пов'язано з JavaScript ("більшість речей є об'єктами'), і як створювати конструктори та екземпляри об'єктів.</td>
+ </tr>
+ </tbody>
+ </table>
+ </th>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="Об'єктно-орієнтоване_програмування_-_основи">Об'єктно-орієнтоване програмування - основи</h2>
+
+<p>Давайте почнемо з спрощеного, високорівневого уявлення про об'єктно-орієнтоване програмування (ООП). Ми говоримо спрощеного, тому що ООП може швидко стати дуже складним, і якщо зараз дати повний курс, ймовірно, можна більше заплутати, ніж допомогти. Основна ідея ООП полягає в тому, що ми використовуємо об'єкти, щоб моделювати реальні речі, які ми хочемо представити всередині наших програм і/або забезпечити простий спосіб доступу до функціональних можливостей, які в іншому випадку було б важко або неможливо використати.</p>
+
+<p>Об'єкти можуть містити пов'язані дані і код, які представляють інформацію про те, що ви намагаєтеся змоделювати, а також функціональні можливості або поведінку, які ви хочете мати. Дані об'єкта (і часто функції теж) можуть бути акуратно збережені (офіційне поняття <strong>інкапсульовані</strong>) всередині об'єктного пакету (якому можна дати певне ім'я для позначення, яке іноді називають <strong>простором імен</strong>),  що полегшує структуру і доступ; об'єкти також часто використовуються як сховища даних, які можна легко відправляти по мережі.</p>
+
+<h3 id="Визначення_шаблону_об'єкта">Визначення шаблону об'єкта</h3>
+
+<p>Давайте розглянемо просту програму, яка відображає інформацію про учнів та вчителів в школі. Тут ми розглянемо теорію ООП загалом, а не в контексті будь-якої конкретної мови програмування.</p>
+
+<p>Щоб почати, повернемося до об'єкта <code>person</code> з нашої статті <a href="https://developer.mozilla.org/uk/docs/Learn/JavaScript/Objects/Basics">Основи об'єктів в JavaScript</a>, який визначає загальні відомості і функціональні можливості людини. Є багато речей, які ви <em>можете</em> дізнатись про людину (її адресу, зріст, розмір взуття, профіль ДНК, номер паспорта, значні особистісні риси ...) , але в цьому випадку нас цікавлять лише ім'я, вік, стать та інтереси, і ми також хочемо написати коротку інформацію про неї на основі цих даних, і отримувати їх, щоб привітатись. Це відомо як <strong>абстракція (abstraction)</strong> - створення простої моделі більш складної речі, яка представляє її найважливіші аспекти таким чином, щоб було зручно працювати для виконання цілей нашої програми.</p>
+
+<p><img alt="" src="https://mdn.mozillademos.org/files/13889/person-diagram.png" style="display: block; height: 219px; margin: 0px auto; width: 610px;"></p>
+
+<p>В деяких мовах ООП, це загальне визначення типу об'єкта називається класом <strong>(class) </strong>(JavaScript використовує інший механізм і термінологію, як ви побачите нижче) - це насправді не об'єкт, це швидше шаблон, який визначає, які характеристики повинен мати об'єкт.</p>
+
+<h3 id="Створення_реальних_об'єктів">Створення реальних об'єктів</h3>
+
+<p>З нашого класу ми можемо створити <strong>екземпляри об'єктів</strong> - об'єкти, що містять дані та функціональні можливості, визначені в класі. З нашого класу Person, можемо створити декілька справжніх людей:</p>
+
+<p><img alt="" src="https://mdn.mozillademos.org/files/15163/MDN-Graphics-instantiation-2-fixed.png" style="display: block; height: 702px; margin: 0px auto; width: 695px;"></p>
+
+<p>Коли екземпляр об'єкта створюється з класу, <strong>функція конструктора</strong> класу виконується для його створення. Цей процес створення екземпляра об'єкта з класу називається <strong>instantiation</strong> - екземпляр об'єкта створюється з класу.</p>
+
+<h3 id="Specialist_classes">Specialist classes</h3>
+
+<p>In this case we don't want generic people — we want teachers and students, which are both more specific types of people. In OOP, we can create new classes based on other classes — these new <strong>child classes</strong> can be made to <strong>inherit</strong> the data and code features of their <strong>parent class</strong>, so you can reuse functionality common to all the object types rather than having to duplicate it.  Where functionality differs between classes, you can define specialized features directly on them as needed.</p>
+
+<p><img alt="" src="https://mdn.mozillademos.org/files/13881/MDN-Graphics-inherited-3.png" style="display: block; height: 743px; margin: 0px auto; width: 700px;"></p>
+
+<p>This is really useful — teachers and students share many common features such as name, gender, and age, so it is convenient to only have to define those features once. You can also define the same feature separately in different classes, as each definition of that feature will be in a different namespace. For example, a student's greeting might be of the form "Yo, I'm [firstName]" (e.g <em>Yo, I'm Sam</em>), whereas a teacher might use something more formal, such as "Hello, my name is [Prefix] [lastName], and I teach [Subject]." (e.g <em>Hello, My name is Mr Griffiths, and I teach Chemistry</em>).</p>
+
+<div class="note">
+<p><strong>Note</strong>: The fancy word for the ability of multiple object types to implement the same functionality is <strong>polymorphism</strong>. Just in case you were wondering.</p>
+</div>
+
+<p>You can now create object instances from your child classes. For example:</p>
+
+<p><img alt="" src="https://mdn.mozillademos.org/files/13885/MDN-Graphics-instantiation-teacher-3.png" style="display: block; height: 743px; margin: 0px auto; width: 700px;"></p>
+
+<p>In the rest of the article, we'll start to look at how OOP theory can be put into practice in JavaScript.</p>
+
+<h2 id="Constructors_and_object_instances">Constructors and object instances</h2>
+
+<p>Some people argue that JavaScript is not a true object-oriented language — for example, its <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/class">class</a></code> statement is just syntactical sugar over existing prototypical inheritance and is not a <code>class</code> in a traditional sense. JavaScript, uses special functions called <strong>constructor functions</strong> to define objects and their features. They are useful because you'll often come across situations in which you don't know how many objects you will be creating; constructors provide the means to create as many objects as you need in an effective way, attaching data and functions to them as required.</p>
+
+<p>When a new object instance is created from a constructor function, its core functionality (as defined by its prototype, which we'll explore in the article <a href="/en-US/docs/Learn/JavaScript/Objects/Object_prototypes">Object prototypes</a>) is not all copied over to the new object like "classic" OO languages — instead the functionality is linked to via a reference chain called a <strong>prototype chain</strong>. So this is not true instantiation, strictly speaking — JavaScript uses a different mechanism to share functionality between objects.</p>
+
+<div class="note">
+<p><strong>Note</strong>: Not being "classic OOP" is not necessarily a bad thing; as mentioned above, OOP can get very complex very quickly, and JavaScript has some nice ways to take advantage of OO features without having to get too deep into it.</p>
+</div>
+
+<p>Let's explore creating classes via constructors and creating object instances from them in JavaScript. First of all, we'd like you to make a new local copy of the <a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/introduction/oojs.html">oojs.html</a> file we saw in our first Objects article.</p>
+
+<h3 id="A_simple_example">A simple example</h3>
+
+<ol>
+ <li>Let's start by looking at how you could define a person with a normal function. Add this function within the <code>script</code> element:
+
+ <pre class="brush: js">function createNewPerson(name) {
+ var obj = {};
+ obj.name = name;
+ obj.greeting = function() {
+ alert('Hi! I\'m ' + this.name + '.');
+ };
+ return obj;
+}</pre>
+ </li>
+ <li>You can now create a new person by calling this function — try the following lines in your browser's JavaScript console:
+ <pre class="brush: js">var salva = createNewPerson('Salva');
+salva.name;
+salva.greeting();</pre>
+ This works well enough, but it is a bit long-winded; if we know we want to create an object, why do we need to explicitly create a new empty object and return it? Fortunately JavaScript provides us with a handy shortcut, in the form of constructor functions — let's make one now!</li>
+ <li>Replace your previous function with the following:
+ <pre class="brush: js">function Person(name) {
+ this.name = name;
+ this.greeting = function() {
+ alert('Hi! I\'m ' + this.name + '.');
+ };
+}</pre>
+ </li>
+</ol>
+
+<p>The constructor function is JavaScript's version of a class. You'll notice that it has all the features you'd expect in a function, although it doesn't return anything or explicitly create an object — it basically just defines properties and methods. You'll see the <code>this</code> keyword being used here as well — it is basically saying that whenever one of these object instances is created, the object's <code>name</code> property will be equal to the name value passed to the constructor call, and the <code>greeting()</code> method will use the name value passed to the constructor call too.</p>
+
+<div class="note">
+<p><strong>Note</strong>: A constructor function name usually starts with a capital letter — this convention is used to make constructor functions easier to recognize in code.</p>
+</div>
+
+<p>So how do we call a constructor to create some objects?</p>
+
+<ol>
+ <li>Add the following lines below your previous code addition:
+ <pre class="brush: js">var person1 = new Person('Bob');
+var person2 = new Person('Sarah');</pre>
+ </li>
+ <li>Save your code and reload it in the browser, and try entering the following lines into your JS console:
+ <pre class="brush: js">person1.name
+person1.greeting()
+person2.name
+person2.greeting()</pre>
+ </li>
+</ol>
+
+<p>Cool! You'll now see that we have two new objects on the page, each of which is stored under a different namespace — when you access their properties and methods, you have to start calls with <code>person1</code> or <code>person2</code>; they are neatly packaged away so they won't clash with other functionality. They do, however, have the same <code>name</code> property and <code>greeting()</code> method available. Note that they are using their own <code>name</code> value that was assigned to them when they were created; this is one reason why it is very important to use <code>this</code>, so they will use their own values, and not some other value.</p>
+
+<p>Let's look at the constructor calls again:</p>
+
+<pre class="brush: js">var person1 = new Person('Bob');
+var person2 = new Person('Sarah');</pre>
+
+<p>In each case, the <code>new</code> keyword is used to tell the browser we want to create a new object instance, followed by the function name with its required parameters contained in parentheses, and the result is stored in a variable — very similar to how a standard function is called. Each instance is created according to this definition:</p>
+
+<pre class="brush: js">function Person(name) {
+ this.name = name;
+ this.greeting = function() {
+ alert('Hi! I\'m ' + this.name + '.');
+ };
+}</pre>
+
+<p>After the new objects have been created, the <code>person1</code> and <code>person2</code> variables contain the following objects:</p>
+
+<pre class="brush: js">{
+ name: 'Bob',
+ greeting: function() {
+ alert('Hi! I\'m ' + this.name + '.');
+ }
+}
+
+{
+ name: 'Sarah',
+ greeting: function() {
+ alert('Hi! I\'m ' + this.name + '.');
+ }
+}</pre>
+
+<p>Note that when we are calling our constructor function, we are defining <code>greeting()</code> every time, which isn't ideal. To avoid this, we can define functions on the prototype instead, which we will look at later.</p>
+
+<h3 id="Creating_our_finished_constructor">Creating our finished constructor</h3>
+
+<p>The example we looked at above was only a simple example to get us started. Let's now get on and create our final <code>Person()</code> constructor function.</p>
+
+<ol>
+ <li>Remove the code you inserted so far, and add in this replacement constructor — this is exactly the same as the simple example in principle, with just a bit more complexity:
+ <pre class="brush: js">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 + '.');
+ };
+}</pre>
+ </li>
+ <li>Now add in the following line below it, to create an object instance from it:
+ <pre class="brush: js">var person1 = new Person('Bob', 'Smith', 32, 'male', ['music', 'skiing']);</pre>
+ </li>
+</ol>
+
+<p>You'll now see that you can access the properties and methods just like we did previously — try these in your JS console:</p>
+
+<pre class="brush: js">person1['age']
+person1.interests[1]
+person1.bio()
+// etc.</pre>
+
+<div class="note">
+<p><strong>Note</strong>: If you are having trouble getting this to work, try comparing your code against our version — see <a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/introduction/oojs-class-finished.html">oojs-class-finished.html</a> (also <a href="http://mdn.github.io/learning-area/javascript/oojs/introduction/oojs-class-finished.html">see it running live</a>).</p>
+</div>
+
+<h3 id="Further_exercises">Further exercises</h3>
+
+<p>To start with, try adding a couple more object creation lines of your own, and try getting and setting the members of the resulting object instances.</p>
+
+<p>In addition, there are a couple of problems with our <code>bio()</code> method — the output always includes the pronoun "He", even if your person is female, or some other preferred gender classification. And the bio will only include two interests, even if more are listed in the <code>interests</code> array. Can you work out how to fix this in the class definition (constructor)? You can put any code you like inside a constructor (you'll probably need a few conditionals and a loop). Think about how the sentences should be structured differently depending on gender, and depending on whether the number of listed interests is 1, 2, or more than 2.</p>
+
+<div class="note">
+<p><strong>Note</strong>: If you get stuck, we have provided an <a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/introduction/oojs-class-further-exercises.html">answer inside our GitHub repo</a> (<a href="http://mdn.github.io/learning-area/javascript/oojs/introduction/oojs-class-further-exercises.html">see it live</a>) — try writing it yourself first though!</p>
+</div>
+
+<h2 id="Other_ways_to_create_object_instances">Other ways to create object instances</h2>
+
+<p>So far we've seen two different ways to create an object instance — <a href="/en-US/docs/Learn/JavaScript/Objects/Basics#Object_basics">declaring an object literal</a>, and using a constructor function (see above).</p>
+
+<p>These make sense, but there are other ways — we want to make you familiar with these in case you come across them in your travels around the Web.</p>
+
+<h3 id="The_Object()_constructor">The Object() constructor</h3>
+
+<p>First of all, you can use the <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object">Object()</a></code> constructor to create a new object. Yes, even generic objects have a constructor, which generates an empty object.</p>
+
+<ol>
+ <li>Try entering this into your browser's JavaScript console:
+ <pre class="brush: js">var person1 = new Object();</pre>
+ </li>
+ <li>This stores an empty object in the <code>person1</code> variable. You can then add properties and methods to this object using dot or bracket notation as desired; try these examples in your console:
+ <pre class="brush: js">person1.name = 'Chris';
+person1['age'] = 38;
+person1.greeting = function() {
+ alert('Hi! I\'m ' + this.name + '.');
+};</pre>
+ </li>
+ <li>You can also pass an object literal to the <code>Object()</code> constructor as a parameter, to prefill it with properties/methods. Try this in your JS console:
+ <pre class="brush: js">var person1 = new Object({
+ name: 'Chris',
+ age: 38,
+ greeting: function() {
+ alert('Hi! I\'m ' + this.name + '.');
+ }
+});</pre>
+ </li>
+</ol>
+
+<h3 id="Using_the_create()_method">Using the create() method</h3>
+
+<p>Constructors can help you give your code order—you can create constructors in one place, then create instances as needed, and it is clear where they came from.</p>
+
+<p>However, some people prefer to create object instances without first creating constructors, especially if they are creating only a few instances of an object. JavaScript has a built-in method called <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create">create()</a></code> that allows you to do that. With it, you can create a new object based on any existing object.</p>
+
+<ol>
+ <li>With your finished exercise from the previous sections loaded in the browser, try this in your JavaScript console:
+ <pre class="brush: js">var person2 = Object.create(person1);</pre>
+ </li>
+ <li>Now try these:
+ <pre class="brush: js">person2.name
+person2.greeting()</pre>
+ </li>
+</ol>
+
+<p>You'll see that <code>person2</code> has been created based on <code>person1</code>—it has the same properties and method available to it.</p>
+
+<p>One limitation of <code>create()</code> is that IE8 does not support it. So constructors may be more effective if you want to support older browsers.</p>
+
+<p>We'll explore the effects of <code>create()</code> in more detail later on.</p>
+
+<h2 id="Summary">Summary</h2>
+
+<p>This article has provided a simplified view of object-oriented theory — this isn't the whole story, but it gives you an idea of what we are dealing with here. In addition, we have started to look at how JavaScript relates to and how it differs from "classic OOP", how to implement classes in JavaScript using constructor functions, and different ways of generating object instances.</p>
+
+<p>In the next article, we'll explore JavaScript object prototypes.</p>
+
+<p>{{PreviousMenuNext("Learn/JavaScript/Objects/Basics", "Learn/JavaScript/Objects/Object_prototypes", "Learn/JavaScript/Objects")}}</p>
+
+<p> </p>
+
+<h2 id="In_this_module">In this module</h2>
+
+<ul>
+ <li><a href="/en-US/docs/Learn/JavaScript/Objects/Basics">Object basics</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Objects/Object-oriented_JS">Object-oriented JavaScript for beginners</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Objects/Object_prototypes">Object prototypes</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Objects/Inheritance">Inheritance in JavaScript</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Objects/JSON">Working with JSON data</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Objects/Object_building_practice">Object building practice</a></li>
+ <li><a href="/en-US/docs/Learn/JavaScript/Objects/Adding_bouncing_balls_features">Adding features to our bouncing balls demo</a></li>
+</ul>
+
+<p> </p>