diff options
Diffstat (limited to 'files/fa/learn/javascript')
-rw-r--r-- | files/fa/learn/javascript/index.html | 66 | ||||
-rw-r--r-- | files/fa/learn/javascript/objects/index.html | 49 | ||||
-rw-r--r-- | files/fa/learn/javascript/objects/inheritance/index.html | 436 | ||||
-rw-r--r-- | files/fa/learn/javascript/objects/مقدمات/index.html | 254 |
4 files changed, 805 insertions, 0 deletions
diff --git a/files/fa/learn/javascript/index.html b/files/fa/learn/javascript/index.html new file mode 100644 index 0000000000..2e6649a258 --- /dev/null +++ b/files/fa/learn/javascript/index.html @@ -0,0 +1,66 @@ +--- +title: JavaScript +slug: Learn/JavaScript +tags: + - Beginner + - CodingScripting + - JavaScript + - JavaScripting beginner + - Landing + - Module + - NeedsTranslation + - Topic + - TopicStub + - 'l10n:priority' +translation_of: Learn/JavaScript +--- +<div>{{LearnSidebar}}</div> + +<p class="summary">{{Glossary("JavaScript")}} is a programming language that allows you to implement complex things on web pages. Every time a web page does more than just sit there and display static information for you to look at — displaying timely content updates, or interactive maps, or animated 2D/3D graphics, or scrolling video jukeboxes, and so on — you can bet that JavaScript is probably involved.</p> + +<h2 id="Learning_pathway">Learning pathway</h2> + +<p>JavaScript is arguably more difficult to learn than related technologies such as <a href="/en-US/docs/Learn/HTML">HTML</a> and <a href="/en-US/docs/Learn/CSS">CSS</a>. Before attempting to learn JavaScript, you are strongly advised to get familiar with at least these two technologies first, and perhaps others as well. Start by working through the following modules:</p> + +<ul> + <li><a href="/en-US/docs/Learn/Getting_started_with_the_web">Getting started with the Web</a></li> + <li><a href="/en-US/docs/Web/Guide/HTML/Introduction">Introduction to HTML</a></li> + <li><a href="/en-US/docs/Learn/CSS/Introduction_to_CSS">Introduction to CSS</a></li> +</ul> + +<p>Having previous experience with other programming languages might also help.</p> + +<p>After getting familiar with the basics of JavaScript, you should be in a position to learn about more advanced topics, for example:</p> + +<ul> + <li>JavaScript in depth, as taught in our <a href="/en-US/docs/Web/JavaScript/Guide">JavaScript guide</a></li> + <li><a href="/en-US/docs/Web/API">Web APIs</a></li> +</ul> + +<h2 id="Modules">Modules</h2> + +<p>This topic contains the following modules, in a suggested order for working through them.</p> + +<dl> + <dt><a href="/en-US/docs/Learn/JavaScript/First_steps">JavaScript first steps</a></dt> + <dd>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 JavaScript features in detail, such as variables, strings, numbers and arrays.</dd> + <dt><a href="/en-US/docs/Learn/JavaScript/Building_blocks">JavaScript building blocks</a></dt> + <dd>In this module, we continue our coverage of all JavaScript's key fundamental features, turning our attention to commonly-encountered types of code block such as conditional statements, loops, functions, and events. You've seen this stuff already in the course, but only in passing — here we'll discuss it all explicitly.</dd> + <dt><a href="/en-US/docs/Learn/JavaScript/Objects">Introducing JavaScript objects</a></dt> + <dd>In JavaScript, most things are objects, from core JavaScript features like strings and arrays to the browser APIs built on top of JavaScript. You can even create your own objects to encapsulate related functions and variables into efficient packages. The object-oriented nature of JavaScript is important to understand if you want to go further with your knowledge of the language and write more efficient code, therefore we've provided this module to help you. Here we teach object theory and syntax in detail, look at how to create your own objects, and explain what JSON data is and how to work with it.</dd> + <dt><a href="/en-US/docs/Learn/JavaScript/Client-side_web_APIs">Client-side web APIs</a></dt> + <dd>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. </dd> +</dl> + +<h2 id="Solving_common_JavaScript_problems">Solving common JavaScript problems</h2> + +<p><a href="/en-US/docs/Learn/JavaScript/Howto">Use JavaScript to solve common problems</a> provides links to sections of content explaining how to use JavaScript to solve very common problems when creating a webpage.</p> + +<h2 id="See_also">See also</h2> + +<dl> + <dt><a href="/en-US/docs/Web/JavaScript">JavaScript on MDN</a></dt> + <dd>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.</dd> + <dt><a href="https://www.youtube.com/user/codingmath">Coding math</a></dt> + <dd>An excellent series of video tutorials to teach the math you need to understand to be an effective programmer, by <a href="https://twitter.com/bit101">Keith Peters</a>.</dd> +</dl> diff --git a/files/fa/learn/javascript/objects/index.html b/files/fa/learn/javascript/objects/index.html new file mode 100644 index 0000000000..0e611c58c2 --- /dev/null +++ b/files/fa/learn/javascript/objects/index.html @@ -0,0 +1,49 @@ +--- +title: مقدمه ای بر اشیاء در جاوااسکریپت +slug: Learn/JavaScript/Objects +tags: + - آموزش + - جاوااسکریپت + - راهنما + - شی + - مقاله + - مقدماتی +translation_of: Learn/JavaScript/Objects +--- +<div dir="rtl">{{LearnSidebar}}</div> + +<p class="summary">در جاوااسکریپ، تقریبا همه چیز، از ویژگیهای اصلی آن مثل رشته و آرایه تا API های مرورگر ساخته شده بر پایه جاوااسکریپت، یک شی است. حتی این امکان وجود دارد تا اشیا مورد نظر خود برای تجمیع توابع و متغییرهای مرتبط با هم در یک بسته کارا را تعریف کنید. اگر بخواهید در دانش خود نسبت به این زبان جلوتر بروید، شناخت ذات شی-پایه جاوااسکریپت ضروری مینماید. به همین دلیل ما برای کمک شما این بخش را آماده کردهایم. در این بخش ابتدا تئوری اشیاء و رسم الخط آن را به جزء بررسی کرده و سپس به چگونگی ساخت اشیاء اختصاصی نگاهی خواهیم انداخت.</p> + +<h2 id="پیشنیازها">پیشنیازها</h2> + +<p dir="rtl">پیش از شروع این بخش، شما باید با HTML و CSS تا حدی آشنایی داشته باشید. توصیه میشود که بخشهای <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Introduction">مقدمهای بر HTML</a> و <a href="https://developer.mozilla.org/en-US/docs/Learn/CSS/Introduction_to_CSS">مقدمهای بر CSS</a> را قبل از شروع با جاوااسکریپت را کار کنید.</p> + +<p dir="rtl">همچنین لازم است قبل از شروع کار با اشیا در جاوااسکریپت، تا حدودی با اصول آن آشنا باشید. پیش از مطالعه این بخش، <a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps">قدمهای اول در جاوااسکریپت</a> و <a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks">بلوکهای سازنده جاوااسکریپت</a> را مطالعه بنمایید.</p> + +<div class="note" dir="rtl"> +<p><strong>نکته</strong>: اگر شما روی کامپیوتر/تبلت/ یا سایر دستگاهها کار میکنید و شما توانایی تولید فایلهای خود را ندارید، میتوانید (بسیاری از) نمونه کدها را در برنامههای کدنویسی آنلاین مثل <a href="http://jsbin.com/">JSBin</a> و <a href="https://thimble.mozilla.org/">Thimble</a> اجرا نمایید.</p> +</div> + +<h2 id="راهنما">راهنما</h2> + +<dl> + <dt dir="rtl"><a href="/en-US/docs/Learn/JavaScript/Objects/Basics">مقدمهای بر اشیاء</a></dt> + <dd dir="rtl">در اولین مقاله به اشیاء در جاوااسکریپت نگاهی خواهیم انداخت، به اصول رسم الخط اشیاء در جاوااسکریپت نگاهی خواهیم انداخت و برخی از ویژگیهای جاوااسکریپت را که تا کنون با آن کار کردهایم را بازنگری میکنیم و این حقیقت را که بسیاری از ویژگیهایی که تا کنون با آنها سروکار داشتهایم در واقع شی بودهاند را بازگو میکنیم.</dd> + <dt dir="rtl"><a href="/en-US/docs/Learn/JavaScript/Objects/Object-oriented_JS">جاوااسکریپت شیگرا برای مبتدیها</a></dt> + <dd dir="rtl">با دانستن اصول اولیه، در این بخش روی جاوااسکریپت شی-گرا تمرکز (OOJS) تمرکز میکنیم — این مقاله دیدی کلی از تئوری برنامه نویسی شی گرا ارائه میکند و سپس چگونگی شبیه سازی کلاسهایی از اشیاء توسز توابع سازنده و چگونگی ساخت نمونه اشیاء را شرح میدهد.</dd> + <dt dir="rtl"><a href="/en-US/docs/Learn/JavaScript/Objects/Object_prototypes">نمونههای اولیه شی</a></dt> + <dd dir="rtl">نمونههای اولیه، مکانیزمی است که اشیا در جاوااسکریپت از یکدیگر ارثبری مینمایند، این مفهوم با مفهوم ارثبری در زبانهای شی گرای سنتی متفاوت است. در این مقاله، این تفاوت را بررسی میکنیم، چگونگی کارکرد زنجیرههای نمونه اولیه را شرح میدهیم و به اینکه چگونه خاصیتهای نمونه اولیه را میتوان برای اضافه کردن توابع به سازندههای موجود استفاده کرد، نگاهی خواهیم انداخت.</dd> + <dt dir="rtl"><a href="/en-US/docs/Learn/JavaScript/Objects/Inheritance">ارثبری در جاوااسکریپت</a></dt> + <dd dir="rtl">با این توضیحات فراوان از OOJS، این مقاله چگونگی ساخت اشیا "فرزند" (سازندهها) و چگونگی ارث بردن ویژگیها از کلاس والد خود شرح میدهیم.</dd> + <dt dir="rtl"><a href="/en-US/docs/Learn/JavaScript/Objects/JSON">کار با دادههای جیسان</a></dt> + <dd dir="rtl">نشانهگذاری شیء جاوااسکریپت (JSON) که معمولا برای نمایش و انتقال داده در وبسایتها (یعنی ارسال داده از سرور به کلاینت به گونهای که بتوان آن را در صفحه وب نمایش داد) استفاده میشود، فرمت متن-پایه استاندارد برای نمایش ساختارمند داده بر اساس نشانگذاری اشیاء در جاوااسکریپت است. شما غالبا با جیسان مواجه میشوید، بنابراین در این مقاله ما به شما هرآنچه را که برای کار با جیسان با استفاده از جاوااسکریپت نیاز دارید، شامل تجزیه جیسان به نحوی که بتوانید به دادههای آن دسترسی داشته باشید و یا جیسان خود را بنویسید، یاد خواهیم داد.</dd> + <dt dir="rtl"><a href="/en-US/docs/Learn/JavaScript/Objects/Object_building_practice">تمرین ساخت شی</a></dt> + <dd dir="rtl">در مقالات قبلی، به همه ضروریات تئوری اشیاء جاوااسکریپت و نشانهگذاری آن نگاه کردیم و به شما پایه محکمی برای شروع دادیم. در این مقاله به داخل تمرین عملی شیرجه میزنیم و به شما تمرین بیشتری از اشیاء اختصاصی جاوااسکریپت میدهیم که با آنها یک چیز جالب و رنگی بسازید — یک توپ شیطانک رنگی!</dd> +</dl> + +<h2 id="Assessments">Assessments</h2> + +<dl> + <dt><a href="/en-US/docs/Learn/JavaScript/Objects/Adding_bouncing_balls_features">Adding features to our bouncing balls demo</a></dt> + <dd>In this assessment, you are expected to use the bouncing balls demo from the previous article as a starting point, and add some new and interesting features to it.</dd> +</dl> diff --git a/files/fa/learn/javascript/objects/inheritance/index.html b/files/fa/learn/javascript/objects/inheritance/index.html new file mode 100644 index 0000000000..c80d22ab3a --- /dev/null +++ b/files/fa/learn/javascript/objects/inheritance/index.html @@ -0,0 +1,436 @@ +--- +title: Inheritance in JavaScript +slug: Learn/JavaScript/Objects/Inheritance +translation_of: Learn/JavaScript/Objects/Inheritance +--- +<div>{{LearnSidebar}}</div> + +<div>{{PreviousMenuNext("Learn/JavaScript/Objects/Object_prototypes", "Learn/JavaScript/Objects/JSON", "Learn/JavaScript/Objects")}}</div> + +<p class="summary">With most of the gory details of OOJS now explained, this article shows how to create "child" object classes (constructors) that inherit features from their "parent" classes. In addition, we present some advice on when and where you might use OOJS, and look at how classes are dealt with in modern ECMAScript syntax.</p> + +<table class="learn-box standard-table"> + <tbody> + <tr> + <th scope="row">Prerequisites:</th> + <td>Basic computer literacy, a basic understanding of HTML and CSS, familiarity with JavaScript basics (see <a href="/en-US/docs/Learn/JavaScript/First_steps">First steps</a> and <a href="/en-US/docs/Learn/JavaScript/Building_blocks">Building blocks</a>) and OOJS basics (see <a href="/en-US/docs/Learn/JavaScript/Object-oriented/Introduction">Introduction to objects</a>).</td> + </tr> + <tr> + <th scope="row">Objective:</th> + <td>To understand how it is possible to implement inheritance in JavaScript.</td> + </tr> + </tbody> +</table> + +<h2 id="وراثت_Prototypal">وراثت Prototypal</h2> + +<p>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?</p> + +<p>Let's explore how to do this with a concrete example.</p> + +<h2 id="Getting_started">Getting started</h2> + +<p>First of all, make yourself a local copy of our <a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/advanced/oojs-class-inheritance-start.html">oojs-class-inheritance-start.html</a> file (see it <a href="http://mdn.github.io/learning-area/javascript/oojs/advanced/oojs-class-inheritance-start.html">running live</a> also). Inside here you'll find the same <code>Person()</code> 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:</p> + +<pre class="brush: js">function Person(first, last, age, gender, interests) { + this.name = { + first, + last + }; + this.age = age; + this.gender = gender; + this.interests = interests; +};</pre> + +<p>The methods are <em>all</em> defined on the constructor's prototype. For example:</p> + +<pre class="brush: js">Person.prototype.greeting = function() { + alert('Hi! I\'m ' + this.name.first + '.'); +};</pre> + +<div class="note"> +<p><strong>Note</strong>: In the source code, you'll also see <code>bio()</code> and <code>farewell()</code> methods defined. Later you'll see how these can be inherited by other constructors.</p> +</div> + +<p>Say we wanted to create a <code>Teacher</code> class, like the one we described in our initial object-oriented definition, which inherits all the members from <code>Person</code>, but also includes:</p> + +<ol> + <li>A new property, <code>subject</code> — this will contain the subject the teacher teaches.</li> + <li>An updated <code>greeting()</code> method, which sounds a bit more formal than the standard <code>greeting()</code> method — more suitable for a teacher addressing some students at school.</li> +</ol> + +<h2 id="تعریف_سازنده_Teacher">تعریف سازنده ()Teacher</h2> + +<p>The first thing we need to do is create a <code>Teacher()</code> constructor — add the following below the existing code:</p> + +<pre class="brush: js">function Teacher(first, last, age, gender, interests, subject) { + Person.call(this, first, last, age, gender, interests); + + this.subject = subject; +}</pre> + +<p>This looks similar to the Person constructor in many ways, but there is something strange here that we've not seen before — the <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call">call()</a></code> 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 <code>this</code> 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.</p> + +<p>We want the <code>Teacher()</code> constructor to take the same parameters as the <code>Person()</code> constructor it is inheriting from, so we specify them all as parameters in the <code>call()</code> invocation.</p> + +<p>The last line inside the constructor simply defines the new <code>subject</code> property that teachers are going to have, which generic people don't have.</p> + +<p>As a note, we could have simply done this:</p> + +<pre class="brush: js">function Teacher(first, last, age, gender, interests, subject) { + this.name = { + first, + last + }; + this.age = age; + this.gender = gender; + this.interests = interests; + this.subject = subject; +}</pre> + +<p>But this is just redefining the properties anew, not inheriting them from <code>Person()</code>, so it defeats the point of what we are trying to do. It also takes more lines of code.</p> + +<h3 id="ارث_بری_از_یک_سازنده_بدون_هیچ_گونه_پارامتری">ارث بری از یک سازنده بدون هیچ گونه پارامتری</h3> + +<p>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 <code>call()</code>. So, for example, if you had something really simple like this:</p> + +<pre class="brush: js">function Brick() { + this.width = 10; + this.height = 20; +}</pre> + +<p>You could inherit the <code>width</code> and <code>height</code> properties by doing this (as well as the other steps described below, of course):</p> + +<pre class="brush: js">function BlueGlassBrick() { + Brick.call(this); + + this.opacity = 0.5; + this.color = 'blue'; +}</pre> + +<p>Note that we've only specified <code>this</code> inside <code>call()</code> — no other parameters are required as we are not inheriting any properties from the parent that are set via parameters.</p> + +<h2 id="Setting_Teachers_prototype_and_constructor_reference">Setting Teacher()'s prototype and constructor reference</h2> + +<p>All is good so far, but we have a problem. We have defined a new constructor, and it has a <code>prototype</code> 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 <code>prototype</code> property. To see this, enter <code>Object.getOwnPropertyNames(Teacher.prototype)</code> into either the text input field or your JavaScript console. Then enter it again, replacing <code>Teacher</code> with <code>Person</code>. Nor does the new constructor <em>inherit</em> those methods. To see this, compare the outputs of <code>Person.prototype.greeting</code> and <code>Teacher.prototype.greeting</code>. We need to get <code>Teacher()</code> to inherit the methods defined on <code>Person()</code>'s prototype. So how do we do that?</p> + +<ol> + <li>Add the following line below your previous addition: + <pre class="brush: js">Teacher.prototype = Object.create(Person.prototype);</pre> + Here our friend <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create">create()</a></code> comes to the rescue again. In this case we are using it to create a new object and make it the value of <code>Teacher.prototype</code>. The new object has <code>Person.prototype</code> as its prototype and will therefore inherit, if and when needed, all the methods available on <code>Person.prototype</code>.</li> + <li>We need to do one more thing before we move on. After adding the last line, <code>Teacher.</code><code>prototype</code>'s <code>constructor</code> property is now equal to <code>Person()</code>, because we just set <code>Teacher.prototype</code> to reference an object that inherits its properties from <code>Person.prototype</code>! Try saving your code, loading the page in a browser, and entering <code>Teacher.prototype.constructor</code> into the console to verify.</li> + <li>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: + <pre class="brush: js">Object.defineProperty(Teacher.prototype, 'constructor', { + value: Teacher, + enumerable: false, // so that it does not appear in 'for in' loop + writable: true });</pre> + </li> + <li>Now if you save and refresh, entering <code>Teacher.prototype.constructor</code> should return <code>Teacher()</code>, as desired, plus we are now inheriting from <code>Person()</code>!</li> +</ol> + +<h2 id="Giving_Teacher_a_new_greeting_function">Giving Teacher() a new greeting() function</h2> + +<p>To finish off our code, we need to define a new <code>greeting()</code> function on the <code>Teacher()</code> constructor.</p> + +<p>The easiest way to do this is to define it on <code>Teacher()</code>'s prototype — add the following at the bottom of your code:</p> + +<pre class="brush: js">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 + '.'); +};</pre> + +<p>This alerts the teacher's greeting, which also uses an appropriate name prefix for their gender, worked out using a conditional statement.</p> + +<h2 id="Trying_the_example_out">Trying the example out</h2> + +<p>Now that you've entered all the code, try creating an object instance from <code>Teacher()</code> by putting the following at the bottom of your JavaScript (or something similar of your choosing):</p> + +<pre class="brush: js">let teacher1 = new Teacher('Dave', 'Griffiths', 31, 'male', ['football', 'cookery'], 'mathematics');</pre> + +<p>Now save and refresh, and try accessing the properties and methods of your new <code>teacher1</code> object, for example:</p> + +<pre class="brush: js">teacher1.name.first; +teacher1.interests[0]; +teacher1.bio(); +teacher1.subject; +teacher1.greeting(); +teacher1.farewell();</pre> + +<p>These should all work just fine. The queries on lines 1, 2, 3, and 6 access members inherited from the generic <code>Person()</code> constructor (class). The query on line 4 accesses a member that is available only on the more specialized <code>Teacher()</code> constructor (class). The query on line 5 would have accessed a member inherited from <code>Person()</code>, except for the fact that <code>Teacher()</code> has its own member with the same name, so the query accesses that member.</p> + +<div class="note"> +<p><strong>Note</strong>: If you have trouble getting this to work, compare your code to our <a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/advanced/oojs-class-inheritance-finished.html">finished version</a> (see it <a href="http://mdn.github.io/learning-area/javascript/oojs/advanced/oojs-class-inheritance-finished.html">running live</a> also).</p> +</div> + +<p>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.</p> + +<p>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 <a href="/en-US/docs/Web/JavaScript/Reference/Classes">Classes</a>). 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.</p> + +<p>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. <a href="http://coffeescript.org/#classes">CoffeeScript</a> for example provides <code>class</code>, <code>extends</code>, etc.</p> + +<h2 id="A_further_exercise">A further exercise</h2> + +<p>In our <a href="/en-US/docs/Learn/JavaScript/Objects/Object-oriented_JS#Object-oriented_programming_from_10000_meters">OOP theory section</a>, we also included a <code>Student</code> class as a concept, which inherits all the features of <code>Person</code>, and also has a different <code>greeting()</code> method from <code>Person</code> that is much more informal than the <code>Teacher</code>'s greeting. Have a look at what the student's greeting looks like in that section, and try implementing your own <code>Student()</code> constructor that inherits all the features of <code>Person()</code>, and implements the different <code>greeting()</code> function.</p> + +<div class="note"> +<p><strong>Note</strong>: If you have trouble getting this to work, have a look at our <a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/advanced/oojs-class-inheritance-student.html">finished version</a> (see it <a href="http://mdn.github.io/learning-area/javascript/oojs/advanced/oojs-class-inheritance-student.html">running live</a> also).</p> +</div> + +<h2 id="Object_member_summary">Object member summary</h2> + +<p>To summarize, you've got four types of property/method to worry about:</p> + +<ol> + <li>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 <code>this.x = x</code> type lines; in built in browser code, they are the members only available to object instances (usually created by calling a constructor using the <code>new</code> keyword, e.g. <code>let myInstance = new myConstructor()</code>).</li> + <li>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, <em>not</em> an instance. For example, <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys">Object.keys()</a></code>. These are also known as <strong>static properties/methods</strong>.</li> + <li>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 <code>prototype</code> property, e.g. <code>myConstructor.prototype.x()</code>.</li> + <li>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 <code>var teacher1 = new Teacher( name = 'Chris' );</code> and then <code>teacher1.name</code>), or an object literal (<code>let teacher1 = { name = 'Chris' }</code> and then <code>teacher1.name</code>).</li> +</ol> + +<p>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.</p> + +<h2 id="ECMAScript_2015_Classes">ECMAScript 2015 Classes</h2> + +<p>ECMAScript 2015 introduces <a href="/en-US/docs/Web/JavaScript/Reference/Classes">class syntax</a> 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.</p> + +<div class="note"> +<p><strong>Note</strong>: 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).</p> +</div> + +<p>Let's look at a rewritten version of the Person example, class-style:</p> + +<pre class="brush: js">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!`); + }; +} +</pre> + +<p>The <a href="/en-US/docs/Web/JavaScript/Reference/Statements/class">class</a> statement indicates that we are creating a new class. Inside this block, we define all the features of the class:</p> + +<ul> + <li>The <code><a href="/en-US/docs/Web/JavaScript/Reference/Classes/constructor">constructor()</a></code> method defines the constructor function that represents our <code>Person</code> class.</li> + <li><code>greeting()</code> and <code>farewell()</code> are class methods. Any methods you want associated with the class are defined inside it, after the constructor. In this example, we've used <a href="/en-US/docs/Web/JavaScript/Reference/Template_literals">template literals</a> rather than string concatenation to make the code easier to read.</li> +</ul> + +<p>We can now instantiate object instances using the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/new"><code>new</code> operator</a>, in just the same way as we did before:</p> + +<pre class="brush: js">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 +</pre> + +<div class="note"> +<p><strong>Note</strong>: 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.</p> +</div> + +<h3 id="Inheritance_with_class_syntax">Inheritance with class syntax</h3> + +<p>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 <code>Teacher</code> class, making it inherit from <code>Person</code> using modern class syntax. This is called creating a subclass or subclassing.</p> + +<p>To create a subclass we use the <a href="/en-US/docs/Web/JavaScript/Reference/Classes/extends">extends keyword</a> to tell JavaScript the class we want to base our class on,</p> + +<pre class="brush: js">class Teacher extends Person { + constructor(subject, grade) { + this.subject = subject; + this.grade = grade; + } +}</pre> + +<p>but there's a little catch.</p> + +<p>Unlike old-school constructor functions where the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/new"><code>new</code> operator</a> does the initialization of <code>this</code> to a newly-allocated object, this isn't automatically initialized for a class defined by the <a href="/en-US/docs/Web/JavaScript/Reference/Classes/extends">extends</a> keyword, i.e the sub-classes.</p> + +<p>Therefore running the above code will give an error:</p> + +<pre class="brush: js">Uncaught ReferenceError: Must call super constructor in derived class before +accessing 'this' or returning from derived constructor</pre> + +<p>For sub-classes, the <code>this</code> 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.</p> + +<p>Here we are extending the <code>Person</code> class — the <code>Teacher</code> sub-class is an extension of the <code>Person</code> class. So for <code>Teacher</code>, the <code>this</code> initialization is done by the <code>Person</code> constructor.</p> + +<p>To call the parent constructor we have to use the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/super"><code>super()</code> operator</a>, like so:</p> + +<pre class="brush: js">class Teacher extends Person { + constructor(subject, grade) { + super(); // Now 'this' is initialized by calling the parent constructor. + this.subject = subject; + this.grade = grade; + } +}</pre> + +<p>There is no point having a sub-class if it doesn't inherit properties from the parent class.<br> + It is good then, that the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/super"><code>super()</code> operator</a> also accepts arguments for the parent constructor.</p> + +<p>Looking back to our <code>Person</code> constructor, we can see it has the following block of code in its constructor method:</p> + +<pre class="brush: js"> constructor(first, last, age, gender, interests) { + this.name = { + first, + last + }; + this.age = age; + this.gender = gender; + this.interests = interests; +} </pre> + +<p>Since the <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/super">super()</a></code> operator is actually the parent class constructor, passing it the necessary arguments of the <code>Parent</code> class constructor will also initialize the parent class properties in our sub-class, thereby inheriting it:</p> + +<pre class="brush: js">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; + } +} +</pre> + +<p>Now when we instantiate <code>Teacher</code> object instances, we can call methods and properties defined on both <code>Teacher</code>and <code>Person</code> as we'd expect:</p> + +<pre class="brush: js">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 +</pre> + +<p>Like we did with Teachers, we could create other subclasses of <code>Person</code> to make them more specialized without modifying the base class.</p> + +<div class="note"> +<p><strong>Note</strong>: You can find this example on GitHub as <a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/advanced/es2015-class-inheritance.html">es2015-class-inheritance.html</a> (<a href="https://mdn.github.io/learning-area/javascript/oojs/advanced/es2015-class-inheritance.html">see it live also</a>).</p> +</div> + +<h2 id="Getters_and_Setters">Getters and Setters</h2> + +<p>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 <code>Teacher</code> example, we may not know what subject the teacher will teach before we create them, or their subject may change between terms.</p> + +<p>We can handle such situations with getters and setters.</p> + +<p>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.</p> + +<p>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.</p> + +<p>The modified <code>Teacher</code> class looks like this:</p> + +<pre class="brush: js">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; + } +} +</pre> + +<p>In our class above we have a getter and setter for the <code>subject</code> property. We use <strong><code>_</code> </strong> 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:</p> + +<ul> + <li>To show the current value of the <code>_subject</code> property of the <code>snape</code> object we can use the <code>snape.subject</code> getter method.</li> + <li>To assign a new value to the <code>_subject</code> property we can use the <code>snape.subject="new value"</code> setter method.</li> +</ul> + +<p>The example below shows the two features in action:</p> + +<pre class="brush: js">// 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" +</pre> + +<div class="note"> +<p><strong>Note</strong>: You can find this example on GitHub as <a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/advanced/es2015-getters-setters.html">es2015-getters-setters.html</a> (<a href="https://mdn.github.io/learning-area/javascript/oojs/advanced/es2015-getters-setters.html">see it live also</a>).</p> +</div> + +<div class="blockIndicator note"> +<p><strong>Note:</strong> 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.</p> +</div> + +<h2 id="When_would_you_use_inheritance_in_JavaScript">When would you use inheritance in JavaScript?</h2> + +<p>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.</p> + +<p>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.</p> + +<p>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.</p> + +<div class="note"> +<p><strong>Note</strong>: Because of the way JavaScript works, with the prototype chain, etc., the sharing of functionality between objects is often called <strong>delegation</strong>. Specialized objects delegate functionality to a generic object type.</p> +</div> + +<p>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.</p> + +<p>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.</p> + +<h2 id="Alternatives_for_extending_the_prototype_chain">Alternatives for extending the prototype chain</h2> + +<p>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 <a href="/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain#Different_ways_to_create_objects_and_the_resulting_prototype_chain">Inheritance and the prototype chain</a> article.</p> + +<h2 id="Summary">Summary</h2> + +<p>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.</p> + +<p>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.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="http://www.objectplayground.com/">ObjectPlayground.com</a> — A really useful interactive learning site for learning about objects.</li> + <li><a href="https://www.manning.com/books/secrets-of-the-javascript-ninja-second-edition">Secrets of the JavaScript Ninja</a>, Chapter 7 — A good book on advanced JavaScript concepts and techniques, by John Resig, Bear Bibeault, and Josip Maras. Chapter 7 covers aspects of prototypes and inheritance really well; you can probably track down a print or online copy fairly easily.</li> + <li><a href="https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/this%20%26%20object%20prototypes/README.md">You Don't Know JS: this & Object Prototypes</a> — Part of Kyle Simpson's excellent series of JavaScript manuals, Chapter 5 in particular looks at prototypes in much more detail than we do here. We've presented a simplified view in this series of articles aimed at beginners, whereas Kyle goes into great depth and provides a more complex but more accurate picture.</li> +</ul> + +<p>{{PreviousMenuNext("Learn/JavaScript/Objects/Object_prototypes", "Learn/JavaScript/Objects/JSON", "Learn/JavaScript/Objects")}}</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> diff --git a/files/fa/learn/javascript/objects/مقدمات/index.html b/files/fa/learn/javascript/objects/مقدمات/index.html new file mode 100644 index 0000000000..47ee37c7a2 --- /dev/null +++ b/files/fa/learn/javascript/objects/مقدمات/index.html @@ -0,0 +1,254 @@ +--- +title: مقدمات اشیا در جاوااسکریپت +slug: Learn/JavaScript/Objects/مقدمات +translation_of: Learn/JavaScript/Objects/Basics +--- +<div>{{LearnSidebar}}</div> + +<div>{{NextMenu("Learn/JavaScript/Objects/Object-oriented_JS", "Learn/JavaScript/Objects")}}</div> + +<p class="summary" dir="rtl"><span style="background-color: #ffffff; color: #333333; display: inline !important; float: none; font-family: Arial,x-locale-body,sans-serif; font-size: 16px; font-style: normal; font-weight: 400; letter-spacing: normal; text-align: start; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;">در اولین مقاله به اشیاء در جاوااسکریپت نگاهی خواهیم انداخت، به اصول رسم الخط اشیاء در جاوااسکریپت نگاهی خواهیم انداخت و برخی از ویژگیهای جاوااسکریپت را که تا کنون با آن کار کردهایم را بازنگری میکنیم و این حقیقت را که بسیاری از ویژگیهایی که تا کنون با آنها سروکار داشتهایم در واقع شی بودهاند را بازگو میکنیم.</span></p> + +<table class="learn-box standard-table" style="height: 239px; width: 575px;"> + <tbody> + <tr> + <th dir="rtl" scope="row">پیشنیازها:</th> + <td dir="rtl">ادبیات اولیه کامپیوتر، فهم مقدماتی HTML و CSS، آشنایی با مقدمات جاوااسکریپت ( <a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps">قدمهای اول در جاوااسکریپت</a> و <a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks">بلوکهای سازنده جاوااسکریپت</a> را ببینید).</td> + </tr> + <tr> + <th dir="rtl" scope="row">اهداف:</th> + <td dir="rtl">یادگیری اصول اولیه برنامه نویسی شی-گرا، ارتباط آن با جاوااسکریپت ("تقریبا همه چیز یک شی است") و چگونگی کار با اشیاء در جاوااسکریپت.</td> + </tr> + </tbody> +</table> + +<h2 dir="rtl" id="مقدمات_اشیاء">مقدمات اشیاء</h2> + +<p dir="rtl">یک شی مجموعه از دادهها و یا عملکردهای مرتبط است (که معمولا شامل تعدادی متغییر و تابع است — در داخل اشیاء به متغییرها خاصیت و به توابع، متد گویند). بیایید با یک نمونه بفهمیم آنها چگونه هستند.</p> + +<p dir="rtl">برای شروع، یک کپی از فالی <a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/introduction/oojs.html">oojs.html</a> ما را دانلود کنید.این فایل یک {{HTMLElement("script")}} برای نوشتن کد ما را فراهم میآورد.</p> + +<p dir="rtl">مشابه بسیاری چیزهای دیگر در جاوااسکریپت، ساخت یک شی با تعریف و مقداردهی یک متغییر آغاز میشود. متن زیر را در کد جاوااسکریپتی که اکنون دارید وارد نموده، ذخیره و رفرش کنید:</p> + +<pre class="brush: js">var person = {};</pre> + +<p dir="rtl">اگر در کنسول جاوااسکریپت <code>person</code> را وارد نمایید و دکه اینتر را بزنید، خروجی زیر را خواهید داشت:</p> + +<pre class="brush: js">[object Object]</pre> + +<p dir="rtl">تبریک! شما اولین شی خود را ساختید. کار انجام شد! اما این شی هنوز خالی است، نمیتواند کار خاصی را انجام دهد، پس بیایید شیمان را آپدیت کنیم تا به شکل زیر در بیاید:</p> + +<pre class="brush: js">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] + '.'); + } +}; +</pre> + +<p dir="rtl">بعد از ذخیره و رفرش، مقادیر زیر را در کنسول جاوااسکریپت مرورگر خود در بخش ابزار توسعه وارد کنید:</p> + +<pre class="brush: js">person.name +person.name[0] +person.age +person.interests[1] +person.bio() +person.greeting()</pre> + +<p dir="rtl">شما حالا مقداری داده و عملکرد داخل شی خود دارید و میتوناید با نشانگذاری سادهای به آن دسترسی داشته باشید.</p> + +<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-finished.html">oojs-finished.html</a> (also <a href="http://mdn.github.io/learning-area/javascript/oojs/introduction/oojs-finished.html">see it running live</a>). 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.</p> +</div> + +<p>So what is going on here? Well, an object is made up of multiple members, each of which has a name (e.g. <code>name</code> and <code>age</code> above), and a value (e.g. <code>['Bob', 'Smith']</code> and <code>32</code>). 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:</p> + +<pre class="brush: js">var objectName = { + member1Name: member1Value, + member2Name: member2Value, + member3Name: member3Value +};</pre> + +<p>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 <strong>properties</strong>. The last two items are functions that allow the object to do something with that data, and are referred to as the object's <strong>methods</strong>.</p> + +<p>An object like this is referred to as an <strong>object literal</strong> — 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.</p> + +<p>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.</p> + +<h2 id="Dot_notation">Dot notation</h2> + +<p>Above, you accessed the object's properties and methods using <strong>dot notation</strong>. The object name (person) acts as the <strong>namespace</strong> — it must be entered first to access anything <strong>encapsulated</strong> 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:</p> + +<pre class="brush: js">person.age +person.interests[1] +person.bio()</pre> + +<h3 id="Sub-namespaces">Sub-namespaces</h3> + +<p>It is even possible to make the value of an object member another object. For example, try changing the name member from</p> + +<pre class="brush: js">name: ['Bob', 'Smith'],</pre> + +<p>to</p> + +<pre class="brush: js">name : { + first: 'Bob', + last: 'Smith' +},</pre> + +<p>Here we are effectively creating a <strong>sub-namespace</strong>. 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:</p> + +<pre class="brush: js">person.name.first +person.name.last</pre> + +<p><strong>Important</strong>: At this point you'll also need to go through your method code and change any instances of</p> + +<pre class="brush: js">name[0] +name[1]</pre> + +<p>to</p> + +<pre class="brush: js">name.first +name.last</pre> + +<p>Otherwise your methods will no longer work.</p> + +<h2 id="Bracket_notation">Bracket notation</h2> + +<p>There is another way to access object properties — using bracket notation. Instead of using these:</p> + +<pre class="brush: js">person.age +person.name.first</pre> + +<p>You can use</p> + +<pre class="brush: js">person['age'] +person['name']['first']</pre> + +<p>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 <strong>associative arrays</strong> — they map strings to values in the same way that arrays map numbers to values.</p> + +<h2 id="Setting_object_members">Setting object members</h2> + +<p>So far we've only looked at retrieving (or <strong>getting</strong>) object members — you can also <strong>set</strong> (update) the value of object members by simply declaring the member you want to set (using dot or bracket notation), like this:</p> + +<pre class="brush: js">person.age = 45; +person['name']['last'] = 'Cratchit';</pre> + +<p>Try entering the above lines, and then getting the members again to see how they've changed, like so:</p> + +<pre class="brush: js">person.age +person['name']['last']</pre> + +<p>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:</p> + +<pre class="brush: js">person['eyes'] = 'hazel'; +person.farewell = function() { alert("Bye everybody!"); }</pre> + +<p>You can now test out your new members:</p> + +<pre class="brush: js">person['eyes'] +person.farewell()</pre> + +<p>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:</p> + +<pre class="brush: js">var myDataName = nameInput.value; +var myDataValue = nameValue.value;</pre> + +<p>we could then add this new member name and value to the <code>person</code> object like this:</p> + +<pre class="brush: js">person[myDataName] = myDataValue;</pre> + +<p>To test this, try adding the following lines into your code, just below the closing curly brace of the <code>person</code> object:</p> + +<pre class="brush: js">var myDataName = 'height'; +var myDataValue = '1.75m'; +person[myDataName] = myDataValue;</pre> + +<p>Now try saving and refreshing, and entering the following into your text input:</p> + +<pre class="brush: js">person.height</pre> + +<p>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.</p> + +<h2 id="What_is_this">What is "this"?</h2> + +<p>You may have noticed something slightly strange in our methods. Look at this one for example:</p> + +<pre class="brush: js">greeting: function() { + alert('Hi! I\'m ' + this.name.first + '.'); +}</pre> + +<p>You are probably wondering what "this" is. The <code>this</code> keyword refers to the current object the code is being written inside — so in this case <code>this</code> is equivalent to <code>person</code>. So why not just write <code>person</code> instead? As you'll see in the <a href="/en-US/docs/Learn/JavaScript/Objects/Object-oriented_JS">Object-oriented JavaScript for beginners</a> article when we start creating constructors, etc., <code>this</code> is very useful — it will always ensure that the correct values are used when a member's context changes (e.g. two different <code>person</code> object instances may have different names, but will want to use their own name when saying their greeting).</p> + +<p>Let's illustrate what we mean with a simplified pair of person objects:</p> + +<pre class="brush: js">var person1 = { + name: 'Chris', + greeting: function() { + alert('Hi! I\'m ' + this.name + '.'); + } +} + +var person2 = { + name: 'Brian', + greeting: function() { + alert('Hi! I\'m ' + this.name + '.'); + } +}</pre> + +<p>In this case, <code>person1.greeting()</code> will output "Hi! I'm Chris."; <code>person2.greeting()</code> on the other hand will output "Hi! I'm Brian.", even though the method's code is exactly the same in each case. As we said earlier, <code>this</code> 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.</p> + +<h2 id="You've_been_using_objects_all_along">You've been using objects all along</h2> + +<p>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 our own basic custom examples.</p> + +<p>So when you used string methods like:</p> + +<pre class="brush: js">myString.split(',');</pre> + +<p>You were using a method available on an instance of the <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String">String</a></code> class. Every time you create a string in your code, that string is automatically created as an instance of <code>String</code>, and therefore has several common methods/properties available on it.</p> + +<p>When you accessed the document object model using lines like this:</p> + +<pre class="brush: js">var myDiv = document.createElement('div'); +var myVideo = document.querySelector('video');</pre> + +<p>You were using methods available on an instance of the <code><a href="/en-US/docs/Web/API/Document">Document</a></code> class. For each webpage loaded, an instance of <code>Document</code> is created, called <code>document</code>, which represents the entire page's structure, content, and other features such as its URL. Again, this means that it has several common methods/properties available on it.</p> + +<p>The same is true of pretty much any other built-in object/API you've been using — <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">Array</a></code>, <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math">Math</a></code>, etc.</p> + +<p>Note that built in Objects/APIs don't always create object instances automatically. As an example, the <a href="/en-US/docs/Web/API/Notifications_API">Notifications API</a> — 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:</p> + +<pre class="brush: js">var myNotification = new Notification('Hello!');</pre> + +<p>Again, we'll look at constructors in a later article.</p> + +<div class="note"> +<p><strong>Note</strong>: It is useful to think about the way objects communicate as <strong>message passing</strong> — when an object needs another object to perform some kind of action often it will send a message to another object via one of its methods, and wait for a response, which we know as a return value.</p> +</div> + +<h2 id="Summary">Summary</h2> + +<p>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 <code>person</code> 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.</p> + +<p>In the next article we'll start to look at object-oriented programming (OOP) theory, and how such techniques can be used in JavaScript.</p> + +<p>{{NextMenu("Learn/JavaScript/Objects/Object-oriented_JS", "Learn/JavaScript/Objects")}}</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> |