diff options
Diffstat (limited to 'files/pt-pt/web/javascript/guide')
4 files changed, 1640 insertions, 0 deletions
diff --git a/files/pt-pt/web/javascript/guide/details_of_the_object_model/index.html b/files/pt-pt/web/javascript/guide/details_of_the_object_model/index.html new file mode 100644 index 0000000000..4f8afaf09a --- /dev/null +++ b/files/pt-pt/web/javascript/guide/details_of_the_object_model/index.html @@ -0,0 +1,736 @@ +--- +title: Detalhes do modelo de objeto +slug: Web/JavaScript/Guide/Details_of_the_Object_Model +tags: + - Guia(2) + - Intermediário + - JavaScript + - Objeto +translation_of: Web/JavaScript/Guide/Details_of_the_Object_Model +original_slug: Web/JavaScript/Guia/Detalhes_do_modelo_de_objeto +--- +<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Working_with_Objects", "Web/JavaScript/Guide/Iterators_and_Generators")}}</div> + +<div class="note"> +<p>The content of this article is under discussion. Please provide feedback and help us to make this page better: {{bug(1201380)}}.</p> +</div> + +<p class="summary">JavaScript is an object-based language based on prototypes, rather than being class-based. Because of this different basis, it can be less apparent how JavaScript allows you to create hierarchies of objects and to have inheritance of properties and their values. This chapter attempts to clarify the situation.</p> + +<p>This chapter assumes that you are already somewhat familiar with JavaScript and that you have used JavaScript functions to create simple objects.</p> + +<h2 id="Linguagens_com_base_em_classe_versus_protótipo">Linguagens com base em classe versus protótipo</h2> + +<p>Class-based object-oriented languages, such as Java and C++, are founded on the concept of two distinct entities: classes and instances.</p> + +<ul> + <li>A <em>class</em> defines all of the properties (considering methods and fields in Java, or members in C++, to be properties) that characterize a certain set of objects. A class is an abstract thing, rather than any particular member of the set of objects it describes. For example, the <code>Employee</code> class could represent the set of all employees.</li> + <li>An <em>instance</em>, on the other hand, is the instantiation of a class; that is, one of its members. For example, <code>Victoria</code> could be an instance of the <code>Employee</code> class, representing a particular individual as an employee. An instance has exactly the same properties of its parent class (no more, no less).</li> +</ul> + +<p>A prototype-based language, such as JavaScript, does not make this distinction: it simply has objects. A prototype-based language has the notion of a <em>prototypical object</em>, an object used as a template from which to get the initial properties for a new object. Any object can specify its own properties, either when you create it or at run time. In addition, any object can be associated as the <em>prototype</em> for another object, allowing the second object to share the first object's properties.</p> + +<h3 id="Definição_de_uma_classe">Definição de uma classe</h3> + +<p>In class-based languages, you define a class in a separate <em>class definition</em>. In that definition you can specify special methods, called <em>constructors</em>, to create instances of the class. A constructor method can specify initial values for the instance's properties and perform other processing appropriate at creation time. You use the <code>new</code> operator in association with the constructor method to create class instances.</p> + +<p>JavaScript follows a similar model, but does not have a class definition separate from the constructor. Instead, you define a constructor function to create objects with a particular initial set of properties and values. Any JavaScript function can be used as a constructor. You use the <code>new</code> operator with a constructor function to create a new object.</p> + +<h3 id="Subclasses_e_sucessão">Subclasses e sucessão</h3> + +<p>In a class-based language, you create a hierarchy of classes through the class definitions. In a class definition, you can specify that the new class is a <em>subclass</em> of an already existing class. The subclass inherits all the properties of the superclass and additionally can add new properties or modify the inherited ones. For example, assume the <code>Employee</code> class includes only the <code>name</code> and <code>dept</code> properties, and <code>Manager</code> is a subclass of <code>Employee</code> that adds the <code>reports</code> property. In this case, an instance of the <code>Manager</code> class would have all three properties: <code>name</code>, <code>dept</code>, and <code>reports</code>.</p> + +<p>JavaScript implements inheritance by allowing you to associate a prototypical object with any constructor function. So, you can create exactly the <code>Employee</code> — <code>Manager</code> example, but you use slightly different terminology. First you define the <code>Employee</code> constructor function, specifying the <code>name</code> and <code>dept</code> properties. Next, you define the <code>Manager</code> constructor function, calling the <code>Empl</code><code>oyee</code> constructor and specifying the <code>reports</code> property. Finally, you assign a new object derived from <code>Employee.prototype</code> as the <code>prototype</code> for the <code>Manager</code> constructor function. Then, when you create a new <code>Manager</code>, it inherits the <code>name</code> and <code>dept</code> properties from the <code>Employee</code> object.</p> + +<h3 id="Adição_e_remoção_de_propriedades">Adição e remoção de propriedades</h3> + +<p>In class-based languages, you typically create a class at compile time and then you instantiate instances of the class either at compile time or at run time. You cannot change the number or the type of properties of a class after you define the class. In JavaScript, however, at run time you can add or remove properties of any object. If you add a property to an object that is used as the prototype for a set of objects, the objects for which it is the prototype also get the new property.</p> + +<h3 id="Resumo_das_diferenças">Resumo das diferenças</h3> + +<p>The following table gives a short summary of some of these differences. The rest of this chapter describes the details of using JavaScript constructors and prototypes to create an object hierarchy and compares this to how you would do it in Java.</p> + +<table class="standard-table"> + <caption>Comparison of class-based (Java) and prototype-based (JavaScript) object systems</caption> + <thead> + <tr> + <th scope="col">Com base em Classe (Java)</th> + <th scope="col">Com base em Protótipo (JavaScript)</th> + </tr> + </thead> + <tbody> + <tr> + <td>Class and instance are distinct entities.</td> + <td>All objects can inherit from another object.</td> + </tr> + <tr> + <td>Define a class with a class definition; instantiate a class with constructor methods.</td> + <td>Define and create a set of objects with constructor functions.</td> + </tr> + <tr> + <td>Create a single object with the <code>new</code> operator.</td> + <td>Same.</td> + </tr> + <tr> + <td>Construct an object hierarchy by using class definitions to define subclasses of existing classes.</td> + <td>Construct an object hierarchy by assigning an object as the prototype associated with a constructor function.</td> + </tr> + <tr> + <td>Inherit properties by following the class chain.</td> + <td>Inherit properties by following the prototype chain.</td> + </tr> + <tr> + <td>Class definition specifies <em>all</em> properties of all instances of a class. Cannot add properties dynamically at run time.</td> + <td>Constructor function or prototype specifies an <em>initial set</em> of properties. Can add or remove properties dynamically to individual objects or to the entire set of objects.</td> + </tr> + </tbody> +</table> + +<h2 id="The_employee_example">The employee example</h2> + +<p>The remainder of this chapter uses the employee hierarchy shown in the following figure.</p> + +<div style="display: table-row;"> +<div style="display: table-cell; width: 350px; text-align: center; vertical-align: middle; padding: 10px;"> +<p>A simple object hierarchy with the following objects:</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/3060/figure8.1.png"></p> +</div> + +<div style="display: table-cell; vertical-align: middle; padding: 10px;"> +<ul> + <li><code>Employee</code> has the properties <code>name</code> (whose value defaults to the empty string) and <code>dept</code> (whose value defaults to "general").</li> + <li><code>Manager</code> is based on <code>Employee</code>. It adds the <code>reports</code> property (whose value defaults to an empty array, intended to have an array of <code>Employee</code> objects as its value).</li> + <li><code>WorkerBee</code> is also based on <code>Employee</code>. It adds the <code>projects</code> property (whose value defaults to an empty array, intended to have an array of strings as its value).</li> + <li><code>SalesPerson</code> is based on <code>WorkerBee</code>. It adds the <code>quota</code> property (whose value defaults to 100). It also overrides the <code>dept</code> property with the value "sales", indicating that all salespersons are in the same department.</li> + <li><code>Engineer</code> is based on <code>WorkerBee</code>. It adds the <code>machine</code> property (whose value defaults to the empty string) and also overrides the <code>dept</code> property with the value "engineering".</li> +</ul> +</div> +</div> + +<h2 id="Criação_de_hierarquia">Criação de hierarquia</h2> + +<p>There are several ways to define appropriate constructor functions to implement the Employee hierarchy. How you choose to define them depends largely on what you want to be able to do in your application.</p> + +<p>This section shows how to use very simple (and comparatively inflexible) definitions to demonstrate how to get the inheritance to work. In these definitions, you cannot specify any property values when you create an object. The newly-created object simply gets the default values, which you can change at a later time.</p> + +<p>In a real application, you would probably define constructors that allow you to provide property values at object creation time (see <a href="#More_flexible_constructors">More flexible constructors</a> for information). For now, these simple definitions demonstrate how the inheritance occurs.</p> + +<p>The following Java and JavaScript <code>Employee</code> definitions are similar. The only difference is that you need to specify the type for each property in Java but not in JavaScript (this is due to Java being a <a href="http://en.wikipedia.org/wiki/Strong_and_weak_typing">strongly typed language</a> while JavaScript is a weakly typed language).</p> + +<div class="twocolumns"> +<h4 id="JavaScript">JavaScript</h4> + +<pre class="brush: js">function Employee() { + this.name = ""; + this.dept = "general"; +} +</pre> + +<h4 id="Java">Java</h4> + +<pre class="brush: java">public class Employee { + public String name = ""; + public String dept = "general"; +} +</pre> +</div> + +<p>The <code>Manager</code> and <code>WorkerBee</code> definitions show the difference in how to specify the next object higher in the inheritance chain. In JavaScript, you add a prototypical instance as the value of the <code>prototype</code> property of the constructor function. You can do so at any time after you define the constructor. In Java, you specify the superclass within the class definition. You cannot change the superclass outside the class definition.</p> + +<div class="twocolumns"> +<h4 id="JavaScript_2">JavaScript</h4> + +<pre class="brush: js">function Manager() { + Employee.call(this); + this.reports = []; +} +Manager.prototype = Object.create(Employee.prototype); + +function WorkerBee() { + Employee.call(this); + this.projects = []; +} +WorkerBee.prototype = Object.create(Employee.prototype); +</pre> + +<h4 id="Java_2">Java</h4> + +<pre class="brush: java">public class Manager extends Employee { + public Employee[] reports = new Employee[0]; +} + + + +public class WorkerBee extends Employee { + public String[] projects = new String[0]; +} + + +</pre> +</div> + +<p>The <code>Engineer</code> and <code>SalesPerson</code> definitions create objects that descend from <code>WorkerBee</code> and hence from <code>Employee</code>. An object of these types has properties of all the objects above it in the chain. In addition, these definitions override the inherited value of the <code>dept</code> property with new values specific to these objects.</p> + +<div class="twocolumns"> +<h4 id="JavaScript_3">JavaScript</h4> + +<pre class="brush: js">function SalesPerson() { + WorkerBee.call(this); + this.dept = "sales"; + this.quota = 100; +} +SalesPerson.prototype = Object.create(WorkerBee.prototype); + +function Engineer() { + WorkerBee.call(this); + this.dept = "engineering"; + this.machine = ""; +} +Engineer.prototype = Object.create(WorkerBee.prototype); +</pre> + +<h4 id="Java_3">Java</h4> + +<pre class="brush: java">public class SalesPerson extends WorkerBee { + public double quota; + public dept = "sales"; + public quota = 100.0; +} + + +public class Engineer extends WorkerBee { + public String machine; + public dept = "engineering"; + public machine = ""; +} + +</pre> +</div> + +<p>Using these definitions, you can create instances of these objects that get the default values for their properties. The next figure illustrates using these JavaScript definitions to create new objects and shows the property values for the new objects.</p> + +<div class="note"> +<p><strong>Nota:</strong> The term <em><em>instance</em></em> has a specific technical meaning in class-based languages. In these languages, an instance is an individual instantiation of a class and is fundamentally different from a class. In JavaScript, "instance" does not have this technical meaning because JavaScript does not have this difference between classes and instances. However, in talking about JavaScript, "instance" can be used informally to mean an object created using a particular constructor function. So, in this example, you could informally say that <code><code>jane</code></code> is an instance of <code><code>Engineer</code></code>. Similarly, although the terms <em><em>parent</em>, <em>child</em>, <em>ancestor</em></em>, and <em><em>descendant</em></em> do not have formal meanings in JavaScript; you can use them informally to refer to objects higher or lower in the prototype chain.</p> +</div> + +<h3 id="Criação_de_objetos_com_definições_simples">Criação de objetos com definições simples</h3> + +<div class="twocolumns"> +<h4 id="Hierarquia_do_objeto">Hierarquia do objeto</h4> + +<p>The following hierarchy is created using the code on the right side.</p> + +<p><img src="https://mdn.mozillademos.org/files/10412/=figure8.3.png"></p> + +<p> </p> + +<h4 id="individual_objects">individual objects</h4> + +<pre class="brush: js">var jim = new Employee; +// jim.name is '' +// jim.dept is 'general' + +var sally = new Manager; +// sally.name is '' +// sally.dept is 'general' +// sally.reports is [] + +var mark = new WorkerBee; +// mark.name is '' +// mark.dept is 'general' +// mark.projects is [] + +var fred = new SalesPerson; +// fred.name is '' +// fred.dept is 'sales' +// fred.projects is [] +// fred.quota is 100 + +var jane = new Engineer; +// jane.name is '' +// jane.dept is 'engineering' +// jane.projects is [] +// jane.machine is '' +</pre> +</div> + +<h2 id="Propriedades_do_objeto">Propriedades do objeto</h2> + +<p>This section discusses how objects inherit properties from other objects in the prototype chain and what happens when you add a property at run time.</p> + +<h3 id="Propriedades_de_sucessão">Propriedades de sucessão</h3> + +<p>Suppose you create the <code>mark</code> object as a <code>WorkerBee</code> with the following statement:</p> + +<pre class="brush: js">var mark = new WorkerBee; +</pre> + +<p>When JavaScript sees the <code>new</code> operator, it creates a new generic object and passes this new object as the value of the <code>this</code> keyword to the <code>WorkerBee</code> constructor function. The constructor function explicitly sets the value of the <code>projects</code> property, and implicitly sets the value of the internal <code>__proto__</code> property to the value of <code>WorkerBee.prototype</code>. (That property name has two underscore characters at the front and two at the end.) The <code>__proto__</code> property determines the prototype chain used to return property values. Once these properties are set, JavaScript returns the new object and the assignment statement sets the variable <code>mark</code> to that object.</p> + +<p>This process does not explicitly put values in the <code>mark</code> object (<em>local</em> values) for the properties that <code>mark</code> inherits from the prototype chain. When you ask for the value of a property, JavaScript first checks to see if the value exists in that object. If it does, that value is returned. If the value is not there locally, JavaScript checks the prototype chain (using the <code>__proto__</code> property). If an object in the prototype chain has a value for the property, that value is returned. If no such property is found, JavaScript says the object does not have the property. In this way, the <code>mark</code> object has the following properties and values:</p> + +<pre class="brush: js">mark.name = ""; +mark.dept = "general"; +mark.projects = []; +</pre> + +<p>The <code>mark</code> object inherits values for the <code>name</code> and <code>dept</code> properties from the prototypical object in <code>mark.__proto__</code>. It is assigned a local value for the <code>projects</code> property by the <code>WorkerBee</code> constructor. This gives you inheritance of properties and their values in JavaScript. Some subtleties of this process are discussed in <a href="#Property_inheritance_revisited">Property inheritance revisited</a>.</p> + +<p>Because these constructors do not let you supply instance-specific values, this information is generic. The property values are the default ones shared by all new objects created from <code>WorkerBee</code>. You can, of course, change the values of any of these properties. So, you could give specific information for <code>mark</code> as follows:</p> + +<pre class="brush: js">mark.name = "Doe, Mark"; +mark.dept = "admin"; +mark.projects = ["navigator"];</pre> + +<h3 id="Adição_de_propriedades">Adição de propriedades</h3> + +<p>In JavaScript, you can add properties to any object at run time. You are not constrained to use only the properties provided by the constructor function. To add a property that is specific to a single object, you assign a value to the object, as follows:</p> + +<pre class="brush: js">mark.bonus = 3000; +</pre> + +<p>Now, the <code>mark</code> object has a <code>bonus</code> property, but no other <code>WorkerBee</code> has this property.</p> + +<p>If you add a new property to an object that is being used as the prototype for a constructor function, you add that property to all objects that inherit properties from the prototype. For example, you can add a <code>specialty</code> property to all employees with the following statement:</p> + +<pre class="brush: js">Employee.prototype.specialty = "none"; +</pre> + +<p>As soon as JavaScript executes this statement, the <code>mark</code> object also has the <code>specialty</code> property with the value of <code>"none"</code>. The following figure shows the effect of adding this property to the <code>Employee</code> prototype and then overriding it for the <code>Engineer</code> prototype.</p> + +<p><img alt="" class="internal" src="/@api/deki/files/4422/=figure8.4.png" style="height: 519px; width: 833px;"><br> + <small><strong>Adding properties</strong></small></p> + +<h2 id="Mais_construtores_flexíveis">Mais construtores flexíveis</h2> + +<p>The constructor functions shown so far do not let you specify property values when you create an instance. As with Java, you can provide arguments to constructors to initialize property values for instances. The following figure shows one way to do this.</p> + +<p><img alt="" class="internal" id="figure8.5" src="/@api/deki/files/4423/=figure8.5.png" style="height: 481px; width: 1012px;"><br> + <small><strong>Specifying properties in a constructor, take 1</strong></small></p> + +<p>The following table shows the Java and JavaScript definitions for these objects.</p> + +<div class="twocolumns"> +<h4 id="JavaScript_4">JavaScript</h4> + +<h4 id="Java_4">Java</h4> +</div> + +<div class="twocolumns"> +<pre class="brush: js">function Employee (name, dept) { + this.name = name || ""; + this.dept = dept || "general"; +} +</pre> + +<p> </p> + +<p> </p> + +<p> </p> + +<p> </p> + +<p> </p> + +<pre class="brush: java">public class Employee { + public String name; + public String dept; + public Employee () { + this("", "general"); + } + public Employee (String name) { + this(name, "general"); + } + public Employee (String name, String dept) { + this.name = name; + this.dept = dept; + } +} +</pre> +</div> + +<div class="twocolumns"> +<pre class="brush: js">function WorkerBee (projs) { + + this.projects = projs || []; +} +WorkerBee.prototype = new Employee; +</pre> + +<p> </p> + +<p> </p> + +<p> </p> + +<pre class="brush: java">public class WorkerBee extends Employee { + public String[] projects; + public WorkerBee () { + this(new String[0]); + } + public WorkerBee (String[] projs) { + projects = projs; + } +} +</pre> +</div> + +<div class="twocolumns"> +<pre class="brush: js"> +function Engineer (mach) { + this.dept = "engineering"; + this.machine = mach || ""; +} +Engineer.prototype = new WorkerBee; +</pre> + +<p> </p> + +<p> </p> + +<p> </p> + +<pre class="brush: java">public class Engineer extends WorkerBee { + public String machine; + public Engineer () { + dept = "engineering"; + machine = ""; + } + public Engineer (String mach) { + dept = "engineering"; + machine = mach; + } +} +</pre> +</div> + +<p>These JavaScript definitions use a special idiom for setting default values:</p> + +<pre class="brush: js">this.name = name || ""; +</pre> + +<p>The JavaScript logical OR operator (<code>||</code>) evaluates its first argument. If that argument converts to true, the operator returns it. Otherwise, the operator returns the value of the second argument. Therefore, this line of code tests to see if <code>name</code> has a useful value for the <code>name</code> property. If it does, it sets <code>this.name</code> to that value. Otherwise, it sets <code>this.name</code> to the empty string. This chapter uses this idiom for brevity; however, it can be puzzling at first glance.</p> + +<div class="note"> +<p><strong>Note:</strong> This may not work as expected if the constructor function is called with arguments which convert to <code><code>false</code></code> (like <code>0</code> (zero) and empty string (<code><code>""</code></code>). In this case the default value will be chosen.</p> +</div> + +<p>With these definitions, when you create an instance of an object, you can specify values for the locally defined properties. You can use the following statement to create a new <code>Engineer</code>:</p> + +<pre class="brush: js">var jane = new Engineer("belau"); +</pre> + +<p><code>Jane</code>'s properties are now:</p> + +<pre class="brush: js">jane.name == ""; +jane.dept == "engineering"; +jane.projects == []; +jane.machine == "belau" +</pre> + +<p>Notice that with these definitions, you cannot specify an initial value for an inherited property such as <code>name</code>. If you want to specify an initial value for inherited properties in JavaScript, you need to add more code to the constructor function.</p> + +<p>So far, the constructor function has created a generic object and then specified local properties and values for the new object. You can have the constructor add more properties by directly calling the constructor function for an object higher in the prototype chain. The following figure shows these new definitions.</p> + +<p><img alt="" class="internal" src="/@api/deki/files/4430/=figure8.6.png" style="height: 534px; width: 1063px;"><br> + <small><strong>Specifying properties in a constructor, take 2</strong></small></p> + +<p>Let's look at one of these definitions in detail. Here's the new definition for the <code>Engineer</code> constructor:</p> + +<pre class="brush: js">function Engineer (name, projs, mach) { + this.base = WorkerBee; + this.base(name, "engineering", projs); + this.machine = mach || ""; +} +</pre> + +<p>Suppose you create a new <code>Engineer</code> object as follows:</p> + +<pre class="brush: js">var jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau"); +</pre> + +<p>JavaScript follows these steps:</p> + +<ol> + <li>The <code>new</code> operator creates a generic object and sets its <code>__proto__</code> property to <code>Engineer.prototype</code>.</li> + <li>The <code>new</code> operator passes the new object to the <code>Engineer</code> constructor as the value of the <code>this</code> keyword.</li> + <li>The constructor creates a new property called <code>base</code> for that object and assigns the value of the <code>WorkerBee</code> constructor to the <code>base</code> property. This makes the <code>WorkerBee</code> constructor a method of the <code>Engineer</code> object.The name of the<code> base</code> property is not special. You can use any legal property name; <code>base</code> is simply evocative of its purpose.</li> + <li> + <p>The constructor calls the <code>base</code> method, passing as its arguments two of the arguments passed to the constructor (<code>"Doe, Jane"</code> and <code>["navigator", "javascript"]</code>) and also the string <code>"engineering"</code>. Explicitly using <code>"engineering"</code> in the constructor indicates that all <code>Engineer</code> objects have the same value for the inherited <code>dept</code> property, and this value overrides the value inherited from <code>Employee</code>.</p> + </li> + <li>Because <code>base</code> is a method of <code>Engineer</code>, within the call to <code>base</code>, JavaScript binds the <code>this</code> keyword to the object created in Step 1. Thus, the <code>WorkerBee</code> function in turn passes the <code>"Doe, Jane"</code> and <code>"engineering"</code> arguments to the <code>Employee</code> constructor function. Upon return from the <code>Employee</code> constructor function, the <code>WorkerBee</code> function uses the remaining argument to set the <code>projects</code> property.</li> + <li>Upon return from the <code>base</code> method, the <code>Engineer</code> constructor initializes the object's <code>machine</code> property to <code>"belau"</code>.</li> + <li>Upon return from the constructor, JavaScript assigns the new object to the <code>jane</code> variable.</li> +</ol> + +<p>You might think that, having called the <code>WorkerBee</code> constructor from inside the <code>Engineer</code> constructor, you have set up inheritance appropriately for <code>Engineer</code> objects. This is not the case. Calling the <code>WorkerBee</code> constructor ensures that an <code>Engineer</code> object starts out with the properties specified in all constructor functions that are called. However, if you later add properties to the <code>Employee</code> or <code>WorkerBee</code> prototypes, those properties are not inherited by the <code>Engineer</code> object. For example, assume you have the following statements:</p> + +<pre class="brush: js">function Engineer (name, projs, mach) { + this.base = WorkerBee; + this.base(name, "engineering", projs); + this.machine = mach || ""; +} +var jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau"); +Employee.prototype.specialty = "none"; +</pre> + +<p>The <code>jane</code> object does not inherit the <code>specialty</code> property. You still need to explicitly set up the prototype to ensure dynamic inheritance. Assume instead you have these statements:</p> + +<pre class="brush: js">function Engineer (name, projs, mach) { + this.base = WorkerBee; + this.base(name, "engineering", projs); + this.machine = mach || ""; +} +Engineer.prototype = new WorkerBee; +var jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau"); +Employee.prototype.specialty = "none"; +</pre> + +<p>Now the value of the <code>jane</code> object's <code>specialty</code> property is "none".</p> + +<p>Another way of inheriting is by using the <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call" title="en-US/docs/JavaScript/Reference/Global Objects/Function/call">call()</a></code> / <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply" title="en-US/docs/JavaScript/Reference/Global Objects/Function/apply"><code>apply()</code></a> methods. Below are equivalent:</p> + +<div class="twocolumns"> +<pre class="brush: js">function Engineer (name, projs, mach) { + this.base = WorkerBee; + this.base(name, "engineering", projs); + this.machine = mach || ""; +} +</pre> + +<pre class="brush: js">function Engineer (name, projs, mach) { + WorkerBee.call(this, name, "engineering", projs); + this.machine = mach || ""; +} +</pre> +</div> + +<p>Using the javascript <code>call()</code> method makes a cleaner implementation because the <code>base</code> is not needed anymore.</p> + +<h2 id="Sucessão_de_propriedade_revisitada">Sucessão de propriedade revisitada</h2> + +<p>The preceding sections described how JavaScript constructors and prototypes provide hierarchies and inheritance. This section discusses some subtleties that were not necessarily apparent in the earlier discussions.</p> + +<h3 id="Valores_locais_versus_sucedidos">Valores locais versus sucedidos</h3> + +<p>When you access an object property, JavaScript performs these steps, as described earlier in this chapter:</p> + +<ol> + <li>Check to see if the value exists locally. If it does, return that value.</li> + <li>If there is not a local value, check the prototype chain (using the <code>__proto__</code> property).</li> + <li>If an object in the prototype chain has a value for the specified property, return that value.</li> + <li>If no such property is found, the object does not have the property.</li> +</ol> + +<p>The outcome of these steps depends on how you define things along the way. The original example had these definitions:</p> + +<pre class="brush: js">function Employee () { + this.name = ""; + this.dept = "general"; +} + +function WorkerBee () { + this.projects = []; +} +WorkerBee.prototype = new Employee; +</pre> + +<p>With these definitions, suppose you create <code>amy</code> as an instance of <code>WorkerBee</code> with the following statement:</p> + +<pre class="brush: js">var amy = new WorkerBee; +</pre> + +<p>The <code>amy</code> object has one local property, <code>projects</code>. The values for the <code>name</code> and <code>dept</code> properties are not local to <code>amy</code> and so derive from the <code>amy</code> object's <code>__proto__</code> property. Thus, <code>amy</code> has these property values:</p> + +<pre class="brush: js">amy.name == ""; +amy.dept == "general"; +amy.projects == []; +</pre> + +<p>Now suppose you change the value of the <code>name</code> property in the prototype associated with <code>Employee</code>:</p> + +<pre class="brush: js">Employee.prototype.name = "Unknown" +</pre> + +<p>At first glance, you might expect that new value to propagate down to all the instances of <code>Employee</code>. However, it does not.</p> + +<p>When you create <em>any</em> instance of the <code>Employee</code> object, that instance gets a local value for the <code>name</code> property (the empty string). This means that when you set the <code>WorkerBee</code> prototype by creating a new <code>Employee</code> object, <code>WorkerBee.prototype</code> has a local value for the <code>name</code> property. Therefore, when JavaScript looks up the <code>name</code> property of the <code>amy</code> object (an instance of <code>WorkerBee</code>), JavaScript finds the local value for that property in <code>WorkerBee.prototype</code>. It therefore does not look further up the chain to <code>Employee.prototype</code>.</p> + +<p>If you want to change the value of an object property at run time and have the new value be inherited by all descendants of the object, you cannot define the property in the object's constructor function. Instead, you add it to the constructor's associated prototype. For example, assume you change the preceding code to the following:</p> + +<pre class="brush: js">function Employee () { + this.dept = "general"; +} +Employee.prototype.name = ""; + +function WorkerBee () { + this.projects = []; +} +WorkerBee.prototype = new Employee; + +var amy = new WorkerBee; + +Employee.prototype.name = "Unknown"; +</pre> + +<p>In this case, the <code>name</code> property of <code>amy</code> becomes "Unknown".</p> + +<p>As these examples show, if you want to have default values for object properties and you want to be able to change the default values at run time, you should set the properties in the constructor's prototype, not in the constructor function itself.</p> + +<h3 id="Determining_instance_relationships">Determining instance relationships</h3> + +<p>Property lookup in JavaScript looks within an object's own properties and, if the property name is not found, it looks within the special object property <code>__proto__</code>. This continues recursively; the process is called "lookup in the prototype chain".</p> + +<p>The special property <code>__proto__</code> is set when an object is constructed; it is set to the value of the constructor's <code>prototype</code> property. So the expression <code>new Foo()</code> creates an object with <code>__proto__ == <code class="moz-txt-verticalline">Foo.prototype</code></code>. Consequently, changes to the properties of <code class="moz-txt-verticalline">Foo.prototype</code> alters the property lookup for all objects that were created by <code>new Foo()</code>.</p> + +<p>Every object has a <code>__proto__</code> object property (except <code>Object</code>); every function has a <code>prototype</code> object property. So objects can be related by 'prototype inheritance' to other objects. You can test for inheritance by comparing an object's <code>__proto__</code> to a function's <code>prototype</code> object. JavaScript provides a shortcut: the <code>instanceof</code> operator tests an object against a function and returns true if the object inherits from the function prototype. For example,</p> + +<pre class="brush: js">var f = new Foo(); +var isTrue = (f instanceof Foo);</pre> + +<p>For a more detailed example, suppose you have the same set of definitions shown in <a href="#Inheriting_properties">Inheriting properties</a>. Create an <code>Engineer</code> object as follows:</p> + +<pre class="brush: js">var chris = new Engineer("Pigman, Chris", ["jsd"], "fiji"); +</pre> + +<p>With this object, the following statements are all true:</p> + +<pre class="brush: js">chris.__proto__ == Engineer.prototype; +chris.__proto__.__proto__ == WorkerBee.prototype; +chris.__proto__.__proto__.__proto__ == Employee.prototype; +chris.__proto__.__proto__.__proto__.__proto__ == Object.prototype; +chris.__proto__.__proto__.__proto__.__proto__.__proto__ == null; +</pre> + +<p>Given this, you could write an <code>instanceOf</code> function as follows:</p> + +<pre class="brush: js">function instanceOf(object, constructor) { + object = object.__proto__; + while (object != null) { + if (object == constructor.prototype) + return true; + if (typeof object == 'xml') { + return constructor.prototype == XML.prototype; + } + object = object.__proto__; + } + return false; +} +</pre> + +<div class="note"><strong>Note:</strong> The implementation above checks the type of the object against "xml" in order to work around a quirk of how XML objects are represented in recent versions of JavaScript. See {{ bug(634150) }} if you want the nitty-gritty details.</div> + +<p>Using the instanceOf function defined above, these expressions are true:</p> + +<pre class="brush: js">instanceOf (chris, Engineer) +instanceOf (chris, WorkerBee) +instanceOf (chris, Employee) +instanceOf (chris, Object) +</pre> + +<p>But the following expression is false:</p> + +<pre class="brush: js">instanceOf (chris, SalesPerson) +</pre> + +<h3 id="Informação_global_nos_construtores">Informação global nos construtores</h3> + +<p>When you create constructors, you need to be careful if you set global information in the constructor. For example, assume that you want a unique ID to be automatically assigned to each new employee. You could use the following definition for <code>Employee</code>:</p> + +<pre class="brush: js">var idCounter = 1; + +function Employee (name, dept) { + this.name = name || ""; + this.dept = dept || "general"; + this.id = idCounter++; +} +</pre> + +<p>With this definition, when you create a new <code>Employee</code>, the constructor assigns it the next ID in sequence and then increments the global ID counter. So, if your next statement is the following, <code>victoria.id</code> is 1 and <code>harry.id</code> is 2:</p> + +<pre class="brush: js">var victoria = new Employee("Pigbert, Victoria", "pubs") +var harry = new Employee("Tschopik, Harry", "sales") +</pre> + +<p>At first glance that seems fine. However, <code>idCounter</code> gets incremented every time an <code>Employee</code> object is created, for whatever purpose. If you create the entire <code>Employee</code> hierarchy shown in this chapter, the <code>Employee</code> constructor is called every time you set up a prototype. Suppose you have the following code:</p> + +<pre class="brush: js">var idCounter = 1; + +function Employee (name, dept) { + this.name = name || ""; + this.dept = dept || "general"; + this.id = idCounter++; +} + +function Manager (name, dept, reports) {...} +Manager.prototype = new Employee; + +function WorkerBee (name, dept, projs) {...} +WorkerBee.prototype = new Employee; + +function Engineer (name, projs, mach) {...} +Engineer.prototype = new WorkerBee; + +function SalesPerson (name, projs, quota) {...} +SalesPerson.prototype = new WorkerBee; + +var mac = new Engineer("Wood, Mac"); +</pre> + +<p>Further assume that the definitions omitted here have the <code>base</code> property and call the constructor above them in the prototype chain. In this case, by the time the <code>mac</code> object is created, <code>mac.id</code> is 5.</p> + +<p>Depending on the application, it may or may not matter that the counter has been incremented these extra times. If you care about the exact value of this counter, one possible solution involves instead using the following constructor:</p> + +<pre class="brush: js">function Employee (name, dept) { + this.name = name || ""; + this.dept = dept || "general"; + if (name) + this.id = idCounter++; +} +</pre> + +<p>When you create an instance of <code>Employee</code> to use as a prototype, you do not supply arguments to the constructor. Using this definition of the constructor, when you do not supply arguments, the constructor does not assign a value to the id and does not update the counter. Therefore, for an <code>Employee</code> to get an assigned id, you must specify a name for the employee. In this example, <code>mac.id</code> would be 1.</p> + +<h3 id="No_multiple_inheritance">No multiple inheritance</h3> + +<p>Some object-oriented languages allow multiple inheritance. That is, an object can inherit the properties and values from unrelated parent objects. JavaScript does not support multiple inheritance.</p> + +<p>Inheritance of property values occurs at run time by JavaScript searching the prototype chain of an object to find a value. Because an object has a single associated prototype, JavaScript cannot dynamically inherit from more than one prototype chain.</p> + +<p>In JavaScript, you can have a constructor function call more than one other constructor function within it. This gives the illusion of multiple inheritance. For example, consider the following statements:</p> + +<pre class="brush: js">function Hobbyist (hobby) { + this.hobby = hobby || "scuba"; +} + +function Engineer (name, projs, mach, hobby) { + this.base1 = WorkerBee; + this.base1(name, "engineering", projs); + this.base2 = Hobbyist; + this.base2(hobby); + this.machine = mach || ""; +} +Engineer.prototype = new WorkerBee; + +var dennis = new Engineer("Doe, Dennis", ["collabra"], "hugo") +</pre> + +<p>Further assume that the definition of <code>WorkerBee</code> is as used earlier in this chapter. In this case, the <code>dennis</code> object has these properties:</p> + +<pre class="brush: js">dennis.name == "Doe, Dennis" +dennis.dept == "engineering" +dennis.projects == ["collabra"] +dennis.machine == "hugo" +dennis.hobby == "scuba" +</pre> + +<p>So <code>dennis</code> does get the <code>hobby</code> property from the <code>Hobbyist</code> constructor. However, assume you then add a property to the <code>Hobbyist</code> constructor's prototype:</p> + +<pre class="brush: js">Hobbyist.prototype.equipment = ["mask", "fins", "regulator", "bcd"] +</pre> + +<p>The <code>dennis</code> object does not inherit this new property.</p> + +<div>{{PreviousNext("Web/JavaScript/Guide/Working_with_Objects", "Web/JavaScript/Guide/Iterators_and_Generators")}}</div> diff --git a/files/pt-pt/web/javascript/guide/grammar_and_types/index.html b/files/pt-pt/web/javascript/guide/grammar_and_types/index.html new file mode 100644 index 0000000000..511fe9d281 --- /dev/null +++ b/files/pt-pt/web/javascript/guide/grammar_and_types/index.html @@ -0,0 +1,642 @@ +--- +title: Gramática e tipos +slug: Web/JavaScript/Guide/Grammar_and_types +tags: + - Guia(2) + - JavaScript +translation_of: Web/JavaScript/Guide/Grammar_and_types +original_slug: Web/JavaScript/Guia/Gramática_e_tipos +--- +<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Introduction", "Web/JavaScript/Guide/Control_flow_and_error_handling")}}</div> + +<p class="summary">Este capítulo discute a gramática básica do JavaScript, declarações de variáveis, tipos de dados e literais.</p> + +<h2 id="Básicos">Básicos</h2> + +<p>JavaScript borrows most of its syntax from Java, but is also influenced by Awk, Perl and Python.</p> + +<p>JavaScript is <strong>case-sensitive</strong> and uses the <strong>Unicode</strong> character set.</p> + +<p>In JavaScript, instructions are called {{Glossary("Statement", "statements")}} and are separated by a semicolon (;). Spaces, tabs and newline characters are called whitespace. The source text of JavaScript scripts gets scanned from left to right and is converted into a sequence of input elements which are tokens, control characters, line terminators, comments or whitespace. ECMAScript also defines certain keywords and literals and has rules for automatic insertion of semicolons (<a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Automatic_semicolon_insertion">ASI</a>) to end statements. However, it is recommended to always add semicolons to end your statements; it will avoid side effects. For more information, see the detailed reference about JavaScript's <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar">lexical grammar</a>.</p> + +<h2 id="Comentários">Comentários</h2> + +<p>The syntax of <strong>comments</strong> is the same as in C++ and in many other languages:</p> + +<pre class="brush: js">// a one line comment + +/* this is a longer, + multi-line comment + */ + +/* You can't, however, /* nest comments */ SyntaxError */</pre> + +<h2 id="Declarações">Declarações</h2> + +<p>There are three kinds of declarations in JavaScript.</p> + +<dl> + <dt>{{jsxref("Statements/var", "var")}}</dt> + <dd>Declares a variable, optionally initializing it to a value.</dd> + <dt>{{experimental_inline}} {{jsxref("Statements/let", "let")}}</dt> + <dd>Declares a block scope local variable, optionally initializing it to a value.</dd> + <dt>{{experimental_inline}} {{jsxref("Statements/const", "const")}}</dt> + <dd>Declares a read-only named constant.</dd> +</dl> + +<h3 id="Variáveis">Variáveis</h3> + +<p>You use variables as symbolic names for values in your application. The names of variables, called {{Glossary("Identifier", "identifiers")}}, conform to certain rules.</p> + +<p>A JavaScript identifier must start with a letter, underscore (_), or dollar sign ($); subsequent characters can also be digits (0-9). Because JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase).</p> + +<p>You can use ISO 8859-1 or Unicode letters such as å and ü in identifiers. You can also use the <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#String_literals">Unicode escape sequences</a> as characters in identifiers.</p> + +<p>Some examples of legal names are <code>Number_hits</code>, <code>temp99</code>, and <code>_name</code>.</p> + +<h3 id="Declararação_de_variáveis">Declararação de variáveis</h3> + +<p>You can declare a variable in three ways:</p> + +<ul> + <li>With the keyword {{jsxref("Statements/var", "var")}}. For example, <code>var x = 42</code>. This syntax can be used to declare both local and global variables.</li> + <li>By simply assigning it a value. For example, <code>x = 42</code>. This always declares a global variable. It generates a strict JavaScript warning. You shouldn't use this variant.</li> + <li>With the keyword {{jsxref("Statements/let", "let")}}. For example, <code>let y = 13</code>. This syntax can be used to declare a block scope local variable. See <a href="#Variable_scope">Variable scope</a> below.</li> +</ul> + +<h3 id="Avaliação_de_variáveis">Avaliação de variáveis</h3> + +<p>A variable declared using the <code>var</code> statement with no initial value specified has the value {{jsxref("undefined")}}.</p> + +<p>An attempt to access an undeclared variable or an attempt to access an identifier declared with let statement before initialization will result in a {{jsxref("ReferenceError")}} exception being thrown:</p> + +<pre class="brush: js">var a; +console.log("The value of a is " + a); // logs "The value of a is undefined" +console.log("The value of b is " + b); // throws ReferenceError exception + +console.log("The value of x is " + x); // throws ReferenceError exception +let x; </pre> + +<p>You can use <code>undefined</code> to determine whether a variable has a value. In the following code, the variable <code>input</code> is not assigned a value, and the <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/if...else" title="en-US/docs/JavaScript/Reference/Statements/if...else">if</a></code> statement evaluates to <code>true</code>.</p> + +<pre class="brush: js">var input; +if(input === undefined){ + doThis(); +} else { + doThat(); +} +</pre> + +<p>The <code>undefined</code> value behaves as <code>false</code> when used in a boolean context. For example, the following code executes the function <code>myFunction</code> because the <code>myArray</code> element is undefined:</p> + +<pre class="brush: js">var myArray = []; +if (!myArray[0]) myFunction(); +</pre> + +<p>The <code>undefined</code> value converts to <code>NaN</code> when used in numeric context.</p> + +<pre class="brush: js">var a; +a + 2; // Evaluates to NaN</pre> + +<p>When you evaluate a {{jsxref("null")}} variable, the null value behaves as 0 in numeric contexts and as false in boolean contexts. For example:</p> + +<pre class="brush: js">var n = null; +console.log(n * 32); // Will log 0 to the console +</pre> + +<h3 id="Variable_scope">Variable scope</h3> + +<p>When you declare a variable outside of any function, it is called a <em>global</em> variable, because it is available to any other code in the current document. When you declare a variable within a function, it is called a <em>local</em> variable, because it is available only within that function.</p> + +<p>JavaScript before ECMAScript 2015 does not have <a href="/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#Block_statement" title="en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#Block_statement">block statement</a> scope; rather, a variable declared within a block is local to the <em>function (or global scope)</em> that the block resides within. For example the following code will log <code>5</code>, because the scope of <code>x</code> is the function (or global context) within which <code>x</code> is declared, not the block, which in this case is an <code>if</code> statement.</p> + +<pre class="brush: js">if (true) { + var x = 5; +} +console.log(x); // 5 +</pre> + +<p>This behavior changes, when using the <code>let</code> declaration introduced in ECMAScript 2015.</p> + +<pre class="brush: js">if (true) { + let y = 5; +} +console.log(y); // ReferenceError: y is not defined +</pre> + +<h3 id="Variable_hoisting">Variable hoisting</h3> + +<p>Another unusual thing about variables in JavaScript is that you can refer to a variable declared later, without getting an exception. This concept is known as <strong>hoisting</strong>; variables in JavaScript are in a sense "hoisted" or lifted to the top of the function or statement. However, variables that are hoisted will return a value of <code>undefined</code>. So even if you declare and initialize after you use or refer to this variable, it will still return undefined.</p> + +<pre class="brush: js">/** + * Example 1 + */ +console.log(x === undefined); // true +var x = 3; + +/** + * Example 2 + */ +// will return a value of undefined +var myvar = "my value"; + +(function() { + console.log(myvar); // undefined + var myvar = "local value"; +})(); +</pre> + +<p>The above examples will be interpreted the same as:</p> + +<pre class="brush: js">/** + * Example 1 + */ +var x; +console.log(x === undefined); // true +x = 3; + +/** + * Example 2 + */ +var myvar = "my value"; + +(function() { + var myvar; + console.log(myvar); // undefined + myvar = "local value"; +})(); +</pre> + +<p>Because of hoisting, all <code>var</code> statements in a function should be placed as near to the top of the function as possible. This best practice increases the clarity of the code.</p> + +<p>In ECMAScript 2015, <code>let (const)</code> <strong>will not hoist</strong> the variable to the top of the block. However, referencing the variable in the block before the variable declaration results in a <code><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/ReferenceError" title="TypeError">ReferenceError</a>.</code> The variable is in a "temporal dead zone" from the start of the block until the declaration is processed.</p> + +<pre class="brush: js">console.log(x); // <code>ReferenceError</code> +let x = 3;</pre> + +<h3 id="Variáveis_gGlobais">Variáveis gGlobais</h3> + +<p>Global variables are in fact properties of the <em>global object</em>. In web pages the global object is {{domxref("window")}}, so you can set and access global variables using the <code>window.<em>variable</em></code> syntax.</p> + +<p>Consequently, you can access global variables declared in one window or frame from another window or frame by specifying the window or frame name. For example, if a variable called <code>phoneNumber</code> is declared in a document, you can refer to this variable from an iframe as <code>parent.phoneNumber</code>.</p> + +<h3 id="Constantes">Constantes</h3> + +<p>You can create a read-only, named constant with the {{jsxref("Statements/const", "const")}} keyword. The syntax of a constant identifier is the same as for a variable identifier: it must start with a letter, underscore or dollar sign and can contain alphabetic, numeric, or underscore characters.</p> + +<pre class="brush: js">const PI = 3.14; +</pre> + +<p>A constant cannot change value through assignment or be re-declared while the script is running. It has to be initialized to a value.</p> + +<p>The scope rules for constants are the same as those for <code>let</code> block scope variables. If the <code>const</code> keyword is omitted, the identifier is assumed to represent a variable.</p> + +<p>You cannot declare a constant with the same name as a function or variable in the same scope. For example:</p> + +<pre class="brush: js">// THIS WILL CAUSE AN ERROR +function f() {}; +const f = 5; + +// THIS WILL CAUSE AN ERROR ALSO +function f() { + const g = 5; + var g; + + //statements +} +</pre> + +<p>However, object attributes are not protected, so the following statement is executed without problems.</p> + +<pre class="brush: js"><code>const MY_OBJECT = {"key": "value"}; +MY_OBJECT.key = "otherValue";</code></pre> + +<h2 id="Estruturas_e_tipode_dados">Estruturas e tipode dados</h2> + +<h3 id="tipos_de_dados">tipos de dados</h3> + +<p>The latest ECMAScript standard defines seven data types:</p> + +<ul> + <li>Six data types that are {{Glossary("Primitive", "primitives")}}: + <ul> + <li>{{Glossary("Boolean")}}. <code>true</code> and <code>false</code>.</li> + <li>{{Glossary("null")}}. A special keyword denoting a null value. Because JavaScript is case-sensitive, <code>null</code> is not the same as <code>Null</code>, <code>NULL</code>, or any other variant.</li> + <li>{{Glossary("undefined")}}. A top-level property whose value is undefined.</li> + <li>{{Glossary("Number")}}. <code>42</code> or <code>3.14159</code>.</li> + <li>{{Glossary("String")}}. "Howdy"</li> + <li>{{Glossary("Symbol")}} (new in ECMAScript 2015). A data type whose instances are unique and immutable.</li> + </ul> + </li> + <li>and {{Glossary("Object")}}</li> +</ul> + +<p>Although these data types are a relatively small amount, they enable you to perform useful functions with your applications. {{jsxref("Object", "Objects")}} and {{jsxref("Function", "functions")}} are the other fundamental elements in the language. You can think of objects as named containers for values, and functions as procedures that your application can perform.</p> + +<h3 id="Conversão_de_tipo_de_dados">Conversão de tipo de dados</h3> + +<p>JavaScript is a dynamically typed language. That means you don't have to specify the data type of a variable when you declare it, and data types are converted automatically as needed during script execution. So, for example, you could define a variable as follows:</p> + +<pre class="brush: js">var answer = 42; +</pre> + +<p>And later, you could assign the same variable a string value, for example:</p> + +<pre class="brush: js">answer = "Thanks for all the fish..."; +</pre> + +<p>Because JavaScript is dynamically typed, this assignment does not cause an error message.</p> + +<p>In expressions involving numeric and string values with the + operator, JavaScript converts numeric values to strings. For example, consider the following statements:</p> + +<pre class="brush: js">x = "The answer is " + 42 // "The answer is 42" +y = 42 + " is the answer" // "42 is the answer" +</pre> + +<p>In statements involving other operators, JavaScript does not convert numeric values to strings. For example:</p> + +<pre class="brush: js">"37" - 7 // 30 +"37" + 7 // "377" +</pre> + +<h3 id="Conversão_de_strings_para_números">Conversão de strings para números</h3> + +<p>In the case that a value representing a number is in memory as a string, there are methods for conversion.</p> + +<ul> + <li id="parseInt()_and_parseFloat()">{{jsxref("parseInt", "parseInt()")}}</li> + <li>{{jsxref("parseFloat", "parseFloat()")}}</li> +</ul> + +<p><code>parseInt</code> will only return whole numbers, so its use is diminished for decimals. Additionally, a best practice for <code>parseInt</code> is to always include the radix parameter. The radix parameter is used to specify which numerical system is to be used.</p> + +<p>An alternative method of retrieving a number from a string is with the <code>+</code> (unary plus) operator:</p> + +<pre class="brush: js">"1.1" + "1.1" = "1.11.1" +(+"1.1") + (+"1.1") = 2.2 +// Note: the parentheses are added for clarity, not required.</pre> + +<h2 id="Literais">Literais</h2> + +<p>You use literals to represent values in JavaScript. These are fixed values, not variables, that you <em>literally</em> provide in your script. This section describes the following types of literals:</p> + +<ul> + <li>{{anch("Array literals")}}</li> + <li>{{anch("Boolean literals")}}</li> + <li>{{anch("Floating-point literals")}}</li> + <li>{{anch("Integers")}}</li> + <li>{{anch("Object literals")}}</li> + <li>{{anch("RegExp literals")}}</li> + <li>{{anch("String literals")}}</li> +</ul> + +<h3 id="Literais_de_tabela">Literais de tabela</h3> + +<p>An array literal is a list of zero or more expressions, each of which represents an array element, enclosed in square brackets (<code>[]</code>). When you create an array using an array literal, it is initialized with the specified values as its elements, and its length is set to the number of arguments specified.</p> + +<p>The following example creates the <code>coffees</code> array with three elements and a length of three:</p> + +<pre class="brush: js">var coffees = ["French Roast", "Colombian", "Kona"]; +</pre> + +<div class="note"> +<p><strong>Note :</strong> An array literal is a type of object initializer. See <a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Using_object_initializers" title="en-US/docs/JavaScript/Guide/Working with Objects#Using Object Initializers">Using Object Initializers</a>.</p> +</div> + +<p>If an array is created using a literal in a top-level script, JavaScript interprets the array each time it evaluates the expression containing the array literal. In addition, a literal used in a function is created each time the function is called.</p> + +<p>Array literals are also <code>Array</code> objects. See {{jsxref("Array")}} and <a href="/en-US/docs/Web/JavaScript/Guide/Indexed_collections">Indexed collections</a> for details on <code>Array</code> objects.</p> + +<h4 id="Extra_commas_in_array_literals">Extra commas in array literals</h4> + +<p>You do not have to specify all elements in an array literal. If you put two commas in a row, the array is created with <code>undefined</code> for the unspecified elements. The following example creates the <code>fish</code> array:</p> + +<pre class="brush: js">var fish = ["Lion", , "Angel"]; +</pre> + +<p>This array has two elements with values and one empty element (<code>fish[0]</code> is "Lion", <code>fish[1]</code> is <code>undefined</code>, and <code>fish[2]</code> is "Angel").</p> + +<p>If you include a trailing comma at the end of the list of elements, the comma is ignored. In the following example, the length of the array is three. There is no <code>myList[3]</code>. All other commas in the list indicate a new element.</p> + +<div class="note"> +<p><strong>Nota :</strong> Trailing commas can create errors in older browser versions and it is a best practice to remove them.</p> +</div> + +<pre class="brush: js">var myList = ['home', , 'school', ]; +</pre> + +<p>In the following example, the length of the array is four, and <code>myList[0]</code> and <code>myList[2]</code> are missing.</p> + +<pre class="brush: js">var myList = [ , 'home', , 'school']; +</pre> + +<p>In the following example, the length of the array is four, and <code>myList[1]</code> and <code>myList[3]</code> are missing. Only the last comma is ignored.</p> + +<pre class="brush: js">var myList = ['home', , 'school', , ]; +</pre> + +<p>Understanding the behavior of extra commas is important to understanding JavaScript as a language, however when writing your own code: explicitly declaring the missing elements as <code>undefined</code> will increase your code's clarity and maintainability.</p> + +<h3 id="Lietrais_boolianas">Lietrais boolianas</h3> + +<p>The Boolean type has two literal values: <code>true</code> and <code>false</code>.</p> + +<p>Do not confuse the primitive Boolean values <code>true</code> and <code>false</code> with the true and false values of the Boolean object. The Boolean object is a wrapper around the primitive Boolean data type. See {{jsxref("Boolean")}} for more information.</p> + +<h3 id="Íntegros">Íntegros</h3> + +<p>Integers can be expressed in decimal (base 10), hexadecimal (base 16), octal (base 8) and binary (base 2).</p> + +<ul> + <li>Decimal integer literal consists of a sequence of digits without a leading 0 (zero).</li> + <li>Leading 0 (zero) on an integer literal, or leading 0o (or 0O) indicates it is in octal. Octal integers can include only the digits 0-7.</li> + <li>Leading 0x (or 0X) indicates hexadecimal. Hexadecimal integers can include digits (0-9) and the letters a-f and A-F.</li> + <li> + <p>Leading 0b (or 0B) indicates binary. Binary integers can include digits only 0 and 1.</p> + </li> +</ul> + +<p>Some examples of integer literals are:</p> + +<pre class="eval">0, 117 and -345 (decimal, base 10) +015, 0001 and -0o77 (octal, base 8) +0x1123, 0x00111 and -0xF1A7 (hexadecimal, "hex" or base 16) +0b11, 0b0011 and -0b11 (binary, base 2) +</pre> + +<p>For more information, see <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Numeric_literals">Numeric literals in the Lexical grammar reference</a>.</p> + +<h3 id="Literais_de_ponto_flutuante">Literais de ponto flutuante</h3> + +<p>A floating-point literal can have the following parts:</p> + +<ul> + <li>A decimal integer which can be signed (preceded by "+" or "-"),</li> + <li>A decimal point ("."),</li> + <li>A fraction (another decimal number),</li> + <li>An exponent.</li> +</ul> + +<p>The exponent part is an "e" or "E" followed by an integer, which can be signed (preceded by "+" or "-"). A floating-point literal must have at least one digit and either a decimal point or "e" (or "E").</p> + +<p>More succinctly, the syntax is:</p> + +<pre class="eval">[(+|-)][digits][.digits][(E|e)[(+|-)]digits] +</pre> + +<p>For example:</p> + +<pre class="eval">3.1415926 +-.123456789 +-3.1E+12 +.1e-23 +</pre> + +<h3 id="Literais_de_objeto">Literais de objeto</h3> + +<p>An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces (<code>{}</code>). You should not use an object literal at the beginning of a statement. This will lead to an error or not behave as you expect, because the { will be interpreted as the beginning of a block.</p> + +<p>The following is an example of an object literal. The first element of the <code>car</code> object defines a property, <code>myCar</code>, and assigns to it a new string, "<code>Saturn</code>"; the second element, the <code>getCar</code> property, is immediately assigned the result of invoking the function <code>(carTypes("Honda"));</code> the third element, the <code>special</code> property, uses an existing variable (<code>sales</code>).</p> + +<pre class="brush: js">var sales = "Toyota"; + +function carTypes(name) { + if (name === "Honda") { + return name; + } else { + return "Sorry, we don't sell " + name + "."; + } +} + +var car = { myCar: "Saturn", getCar: carTypes("Honda"), special: sales }; + +console.log(car.myCar); // Saturn +console.log(car.getCar); // Honda +console.log(car.special); // Toyota +</pre> + +<p>Additionally, you can use a numeric or string literal for the name of a property or nest an object inside another. The following example uses these options.</p> + +<pre class="brush: js">var car = { manyCars: {a: "Saab", "b": "Jeep"}, 7: "Mazda" }; + +console.log(car.manyCars.b); // Jeep +console.log(car[7]); // Mazda +</pre> + +<p>Object property names can be any string, including the empty string. If the property name would not be a valid JavaScript {{Glossary("Identifier","identifier")}} or number, it must be enclosed in quotes. Property names that are not valid identifiers also cannot be accessed as a dot (<code>.</code>) property, but can be accessed and set with the array-like notation("<code>[]</code>").</p> + +<pre class="brush: js">var unusualPropertyNames = { + "": "An empty string", + "!": "Bang!" +} +console.log(unusualPropertyNames.""); // SyntaxError: Unexpected string +console.log(unusualPropertyNames[""]); // An empty string +console.log(unusualPropertyNames.!); // SyntaxError: Unexpected token ! +console.log(unusualPropertyNames["!"]); // Bang!</pre> + +<p>In ES2015, object literals are extended to support setting the prototype at construction, shorthand for <code>foo: foo</code> assignments, defining methods, making super calls, and computing property names with expressions. Together, these also bring object literals and class declarations closer together, and let object-based design benefit from some of the same conveniences.</p> + +<pre class="brush: js">var obj = { + // __proto__ + __proto__: theProtoObj, + // Shorthand for ‘handler: handler’ + handler, + // Methods + toString() { + // Super calls + return "d " + super.toString(); + }, + // Computed (dynamic) property names + [ 'prop_' + (() => 42)() ]: 42 +};</pre> + +<p>Por favor, note:</p> + +<pre class="brush: js">var foo = {a: "alpha", 2: "two"}; +console.log(foo.a); // alpha +console.log(foo[2]); // two +//console.log(foo.2); // Error: missing ) after argument list +//console.log(foo[a]); // Error: a is not defined +console.log(foo["a"]); // alpha +console.log(foo["2"]); // two +</pre> + +<h3 id="RegExp_literals">RegExp literals</h3> + +<p>A regex literal is a pattern enclosed between slashes. The following is an example of an regex literal.</p> + +<pre class="brush: js">var re = /ab+c/;</pre> + +<h3 id="Lietrais_de_string">Lietrais de string</h3> + +<p>A string literal is zero or more characters enclosed in double (<code>"</code>) or single (<code>'</code>) quotation marks. A string must be delimited by quotation marks of the same type; that is, either both single quotation marks or both double quotation marks. The following are examples of string literals:</p> + +<pre class="brush: js">"foo" +'bar' +"1234" +"one line \n another line" +"John's cat" +</pre> + +<p>You can call any of the methods of the String object on a string literal value—JavaScript automatically converts the string literal to a temporary String object, calls the method, then discards the temporary String object. You can also use the <code>String.length</code> property with a string literal:</p> + +<pre class="brush: js">console.log("John's cat".length) +// Will print the number of symbols in the string including whitespace. +// In this case, 10. +</pre> + +<p>In ES2015, template literals are also available. Template strings provide syntactic sugar for constructing strings. This is similar to string interpolation features in Perl, Python and more. Optionally, a tag can be added to allow the string construction to be customized, avoiding injection attacks or constructing higher level data structures from string contents.</p> + +<pre class="brush: js">// Basic literal string creation +`In JavaScript '\n' is a line-feed.` + +// Multiline strings +`In JavaScript this is + not legal.` + +// String interpolation +var name = "Bob", time = "today"; +`Hello ${name}, how are you ${time}?` + +// Construct an HTTP request prefix is used to interpret the replacements and construction +POST`http://foo.org/bar?a=${a}&b=${b} + Content-Type: application/json + X-Credentials: ${credentials} + { "foo": ${foo}, + "bar": ${bar}}`(myOnReadyStateChangeHandler);</pre> + +<p>You should use string literals unless you specifically need to use a String object. See {{jsxref("String")}} for details on <code>String</code> objects.</p> + +<h4 id="Using_special_characters_in_strings">Using special characters in strings</h4> + +<p>In addition to ordinary characters, you can also include special characters in strings, as shown in the following example.</p> + +<pre class="brush: js">"one line \n another line" +</pre> + +<p>The following table lists the special characters that you can use in JavaScript strings.</p> + +<table class="standard-table"> + <caption>Table: JavaScript special characters</caption> + <thead> + <tr> + <th scope="col">Cárater</th> + <th scope="col">Significado</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>\0</code></td> + <td>Null Byte</td> + </tr> + <tr> + <td><code>\b</code></td> + <td>Backspace</td> + </tr> + <tr> + <td><code>\f</code></td> + <td>Form feed</td> + </tr> + <tr> + <td><code>\n</code></td> + <td>New line</td> + </tr> + <tr> + <td><code>\r</code></td> + <td>Carriage return</td> + </tr> + <tr> + <td><code>\t</code></td> + <td>Tab</td> + </tr> + <tr> + <td><code>\v</code></td> + <td>Vertical tab</td> + </tr> + <tr> + <td><code>\'</code></td> + <td>Apostrophe or single quote</td> + </tr> + <tr> + <td><code>\"</code></td> + <td>Double quote</td> + </tr> + <tr> + <td><code>\\</code></td> + <td>Backslash character</td> + </tr> + <tr> + <td><code>\<em>XXX</em></code></td> + <td>The character with the Latin-1 encoding specified by up to three octal digits <em>XXX</em> between 0 and 377. For example, \251 is the octal sequence for the copyright symbol.</td> + </tr> + <tr> + </tr> + <tr> + <td><code>\x<em>XX</em></code></td> + <td>The character with the Latin-1 encoding specified by the two hexadecimal digits <em>XX</em> between 00 and FF. For example, \xA9 is the hexadecimal sequence for the copyright symbol.</td> + </tr> + <tr> + </tr> + <tr> + <td><code>\u<em>XXXX</em></code></td> + <td>The Unicode character specified by the four hexadecimal digits <em>XXXX</em>. For example, \u00A9 is the Unicode sequence for the copyright symbol. See <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#String_literals">Unicode escape sequences</a>.</td> + </tr> + <tr> + <td><code>\u<em>{XXXXX}</em></code></td> + <td>Unicode code point escapes. For example, \u{2F804} is the same as the simple Unicode escapes \uD87E\uDC04.</td> + </tr> + </tbody> +</table> + +<h4 id="Escaping_characters">Escaping characters</h4> + +<p>For characters not listed in the table, a preceding backslash is ignored, but this usage is deprecated and should be avoided.</p> + +<p>You can insert a quotation mark inside a string by preceding it with a backslash. This is known as <em>escaping</em> the quotation mark. For example:</p> + +<pre class="brush: js">var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service."; +console.log(quote); +</pre> + +<p>The result of this would be:</p> + +<pre class="eval">He read "The Cremation of Sam McGee" by R.W. Service. +</pre> + +<p>To include a literal backslash inside a string, you must escape the backslash character. For example, to assign the file path <code>c:\temp</code> to a string, use the following:</p> + +<pre class="brush: js">var home = "c:\\temp"; +</pre> + +<p>You can also escape line breaks by preceding them with backslash. The backslash and line break are both removed from the value of the string.</p> + +<pre class="brush: js">var str = "this string \ +is broken \ +across multiple\ +lines." +console.log(str); // this string is broken across multiplelines. +</pre> + +<p>Although JavaScript does not have "heredoc" syntax, you can get close by adding a line break escape and an escaped line break at the end of each line:</p> + +<pre class="brush: js">var poem = +"Roses are red,\n\ +Violets are blue.\n\ +Sugar is sweet,\n\ +and so is foo." +</pre> + +<h2 id="Mais_informação">Mais informação</h2> + +<p>This chapter focuses on basic syntax for declarations and types. To learn more about JavaScript's language constructs, see also the following chapters in this guide:</p> + +<ul> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling">Control flow and error handling</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration">Loops and iteration</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions">Functions</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators">Expressions and operators</a></li> +</ul> + +<p>In the next chapter, we will have a look at control flow constructs and error handling.</p> + +<p>{{PreviousNext("Web/JavaScript/Guide/Introduction", "Web/JavaScript/Guide/Control_flow_and_error_handling")}}</p> diff --git a/files/pt-pt/web/javascript/guide/index.html b/files/pt-pt/web/javascript/guide/index.html new file mode 100644 index 0000000000..50779449a1 --- /dev/null +++ b/files/pt-pt/web/javascript/guide/index.html @@ -0,0 +1,124 @@ +--- +title: Guia de JavaScript +slug: Web/JavaScript/Guide +tags: + - Guía + - JavaScript + - l10n:prioridade +translation_of: Web/JavaScript/Guide +original_slug: Web/JavaScript/Guia +--- +<div>{{jsSidebar("JavaScript Guide")}}</div> + +<p class="summary">The JavaScript Guide shows you how to use <a href="/en-US/docs/Web/JavaScript">JavaScript</a> and gives an overview of the language. If you want to get started with JavaScript or programming in general, consult the articles in the <a href="/en-US/Learn">learning area</a>. If you need exhaustive information about a language feature, have a look at the <a href="/en-US/docs/Web/JavaScript/Reference">JavaScript reference</a>.</p> + +<h2 id="Capítulos">Capítulos</h2> + +<p>This Guide is divided into several chapters:</p> + +<ul class="card-grid"> + <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Introduction">Introdução</a></span> + + <p><a href="/pt-PT/docs/Web/JavaScript/Guia/Introdução">About this guide</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Introduction#What_is_JavaScript">About JavaScript</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Introduction#JavaScript_and_Java">JavaScript and Java</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Introduction#JavaScript_and_the_ECMAScript_Specification">ECMAScript</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Introduction#Getting_started_with_JavaScript">Tools</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Introduction#Hello_world">Hello World</a></p> + </li> + <li><span><a href="/pt-PT/docs/Web/JavaScript/Guia/Gramática_e_tipos">Gramática e tipos</a></span> + <p><a href="/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Basics">Basic syntax & comments</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Declarations">Declarations</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Variable_scope">Variable scope</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Variable_hoisting">Variable hoisting</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Data_structures_and_types">Data structures and types</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Literals">Literals</a></p> + </li> + <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling">Controlo de fluxo e manipulação de erros</a></span> + <p><code><a href="/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#if...else_statement">if...else</a></code><br> + <code><a href="/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#switch_statement">switch</a></code><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#Exception_handling_statements"><code>try</code>/<code>catch</code>/<code>throw</code></a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#Utilizing_Error_objects">Error objects</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#Promises">Promises</a></p> + </li> + <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration">Loops e iteração</a></span> + <p><code><a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for_statement">for</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#while_statement">while</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#do...while_statement">do...while</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#break_statement">break</a>/<a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#continue_statement">continue</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for...in_statement">for..in</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for...of_statement">for..of</a></code></p> + </li> +</ul> + +<ul class="card-grid"> + <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Functions">Funções</a></span> + + <p><a href="/en-US/docs/Web/JavaScript/Guide/Functions#Defining_functions">Defining functions</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Functions#Calling_functions">Calling functions</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Functions#Function_scope">Function scope</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Functions#Closures">Closures</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Functions#Using_the_arguments_object">Arguments</a> & <a href="/en-US/docs/Web/JavaScript/Guide/Functions#Function_parameters">parameters</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Functions#Arrow_functions">Arrow functions</a></p> + </li> + <li><span><a href="/pt-PT/docs/Web/JavaScript/Guia/Guia_expressões_e_operadores">Expressões e operadores</a></span> + <p><a href="/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Assignment_operators">Assignment</a> & <a href="/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Comparison_operators">Comparisons</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Arithmetic_operators">Arithmetic operators</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Bitwise_operators">Bitwise</a> & <a href="/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Logical_operators">logical operators</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Conditional_(ternary)_operator">Conditional (ternary) operator</a></p> + </li> + <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates">Números e datas</a></span><a href="/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates#Numbers"> Number literals</a> + <p><a href="/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates#Number_object"><code>Number</code> object</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates#Math_object"><code>Math</code> object</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates#Date_object"><code>Date</code> object</a></p> + </li> + <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Text_formatting">Formatação de texto</a></span> + <p><a href="/en-US/docs/Web/JavaScript/Guide/Text_formatting#String_literals">String literals</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Text_formatting#String_objects"><code>String</code> object</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Text_formatting#Multi-line_template_literals">Template literals</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Text_formatting#Internationalization">Internationalization</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Regular_Expressions">Regular Expressions</a></p> + </li> +</ul> + +<ul class="card-grid"> + <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Indexed_collections">Coleções indexadas</a></span> + + <p><a href="/en-US/docs/Web/JavaScript/Guide/Indexed_collections#Array_object">Arrays</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Indexed_collections#Typed_Arrays">Typed arrays</a></p> + </li> + <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Keyed_collections">Coleções Keyed</a></span> + <p><code><a href="/en-US/docs/Web/JavaScript/Guide/Keyed_collections#Map_object">Map</a></code><br> + <code><a href="/en-US/docs/Web/JavaScript/Guide/Keyed_collections#WeakMap_object">WeakMap</a></code><br> + <code><a href="/en-US/docs/Web/JavaScript/Guide/Keyed_collections#Set_object">Set</a></code><br> + <code><a href="/en-US/docs/Web/JavaScript/Guide/Keyed_collections#WeakSet_object">WeakSet</a></code></p> + </li> + <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects">Trabalhar com objetos</a></span> + <p><a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Objects_and_properties">Objets e propriedades</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Creating_new_objects">Criação de objetos</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Defining_methods">Definição de métodos</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Defining_getters_and_setters">Getter and setter</a></p> + </li> + <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model">Detalhes do modelo de objeto</a></span> + <p><a href="/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model#Class-based_vs._prototype-based_languages">Prototype-based OOP</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model#Creating_the_hierarchy">Creating object hierarchies</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model#Property_inheritance_revisited">Inheritance</a></p> + </li> +</ul> + +<ul class="card-grid"> + <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators">Iterators e geradores</a></span> + + <p><a href="/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#Iterators">Iterators</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#Iterables">Iterables</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#Generators">Generators</a></p> + </li> + <li><span><a href="/en-US/docs/Web/JavaScript/Guide/Meta_programming">Metadados de programação</a></span> + <p><code><a href="/en-US/docs/Web/JavaScript/Guide/Meta_programming#Proxies">Proxy</a></code><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Meta_programming#Handlers_and_traps">Handlers and traps</a><br> + <a href="/en-US/docs/Web/JavaScript/Guide/Meta_programming#Revocable_Proxy">Revocable Proxy</a><br> + <code><a href="/en-US/docs/Web/JavaScript/Guide/Meta_programming#Reflection">Reflect</a></code></p> + </li> +</ul> + +<p>{{Next("Web/JavaScript/Guide/Introduction")}}</p> diff --git a/files/pt-pt/web/javascript/guide/introduction/index.html b/files/pt-pt/web/javascript/guide/introduction/index.html new file mode 100644 index 0000000000..eddebd2e98 --- /dev/null +++ b/files/pt-pt/web/javascript/guide/introduction/index.html @@ -0,0 +1,138 @@ +--- +title: Introdução +slug: Web/JavaScript/Guide/Introduction +tags: + - Guía + - JavaScript +translation_of: Web/JavaScript/Guide/Introduction +original_slug: Web/JavaScript/Guia/Introdução +--- +<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide", "Web/JavaScript/Guide/Grammar_and_types")}}</div> + +<p class="summary">Este capítulo apresenta a linguagem JavaScript e discuste alguns dos seus conceitos fundamentais.</p> + +<h2 id="O_que_você_já_deveria_saber">O que você já deveria saber</h2> + +<p>Este guia assume que você possuí os seguintes conhecimentos:</p> + +<ul> + <li>Um conhecimento geral sobre Internet e o World Wide Web ({{Glossary("WWW")}}).</li> + <li>Bom conhecimento sobre como desenvolver em HyperText Markup Language ({{Glossary("HTML")}}).</li> + <li>Alguma experiência com programação. Caso seja iniciante nesse mundo, experimente seguir algum dos links com tutoriais que estão presentes na página principal sobre <a href="/pt-PT/docs/Web/JavaScript/Guia">JavaScript</a>.</li> +</ul> + +<h2 id="Onde_encontrar_informação_sobre_JavaScript">Onde encontrar informação sobre JavaScript?</h2> + +<p>A documentação de JavaScript no MDN incluí o seguinte:</p> + +<ul> + <li><a href="/pt-PT/docs/Learn">Aprender a Web</a> fornece informação para iniciantes e introduz os conceitos básicos sobre programação e Internet.</li> + <li><a href="/pt-PT/docs/Web/JavaScript/Guia">Guia de JavaScript</a> (este guia) fornece uma visão geral sobre a linguagem JavaScript e os seus objetos.</li> + <li><a href="/pt-PT/docs/Web/JavaScript/Reference">Referência de JavaScript</a> fornece conteúdos de referência detalhada para JavaScript.</li> +</ul> + +<p>Se for iniciante em JavaScript, comece lendo alguns dos artigos na <a href="/pt-PT/docs/Learn">área de aprendizagem</a> e o <a href="/pt-PT/docs/Web/JavaScript/Guia">Guia de JavaScript</a>. Assim que compreender os fundamentos da linguagem, pode consultar a <a href="/pt-PT/docs/Web/JavaScript/Reference">Referência de JavaScript</a> para obter mais detalhes sobre objetos individuais e declarações.</p> + +<h2 id="O_que_é_JavaScript">O que é JavaScript?</h2> + +<p>JavaScript é uma linguagem de script orientada a objetos e que funciona entre plataformas. É uma linguagem pequena e simples. Ela pode ser rodada num ambiente anfitrião (por exemplo, o browser), o código JavaScript pode estar ligado a objetos do ambiente e fornece controle programático sobre os mesmos.</p> + +<p>O JavaScript contém uma biblioteca padrão de objetos, tais como <code>Array</code>, <code>Date</code>, <code>Math</code>, e um conjunto fundamental de elementos da linguagem tais como operadores, estruturas de controle, e statements. Os elementos básicos do JavaScript podem ser extendidos com objetos adicionais para uma variedade de propósitos, por exemplo:</p> + +<ul> + <li>JavaScript a correr no cliente extende a linguagem básica pois fornece objetos para controlar o browser e o seu Document Object Model (DOM). Por exemplo, extenções de cliente permitem a uma aplicação adicionar elementos num formulário HTML e responder a eventos do utilizador tais como cliques, input adicionado, e navegação na página.</li> + <li>JavaScript a correr no <span style="background-color: #f3a8a3;">servidor </span>extende a linguagem básica ao fornecer objetos relevantes para que isso aconteça. Por exemplo, extenções do lado do servidor permitem que uma aplicação comunique com uma base de dados, garante continuidade de informação entre invocações da aplicação, ou executa manipulações de ficheiros no servidor.</li> +</ul> + +<h2 id="JavaScript_and_Java" name="JavaScript_and_Java">JavaScript e Java</h2> + +<p>JavaScript e Java são linguagens similares em alguns aspetos mas fundamentalmente diferentes noutros. A linguagem JavaScript assemelha-se ao Java mas não tem o static typing nem a validação strong type. O JavaScsript segue a sintaxe de expressões do Java, convenções de nomenclatura e os construtores básicos de controlo de fluxo. Esta última foi a razão pelo qual a linguagem foi renomeada de LiveScript para JavaScript.</p> + +<p>In contrast to Java's compile-time system of classes built by declarations, JavaScript supports a runtime system based on a small number of data types representing numeric, Boolean, and string values. JavaScript has a prototype-based object model instead of the more common class-based object model. The prototype-based model provides dynamic inheritance; that is, what is inherited can vary for individual objects. JavaScript also supports functions without any special declarative requirements. Functions can be properties of objects, executing as loosely typed methods.</p> + +<p>JavaScript is a very free-form language compared to Java. You do not have to declare all variables, classes, and methods. You do not have to be concerned with whether methods are public, private, or protected, and you do not have to implement interfaces. Variables, parameters, and function return types are not explicitly typed.</p> + +<p>Java is a class-based programming language designed for fast execution and type safety. Type safety means, for instance, that you can't cast a Java integer into an object reference or access private memory by corrupting Java bytecodes. Java's class-based model means that programs consist exclusively of classes and their methods. Java's class inheritance and strong typing generally require tightly coupled object hierarchies. These requirements make Java programming more complex than JavaScript programming.</p> + +<p>In contrast, JavaScript descends in spirit from a line of smaller, dynamically typed languages such as HyperTalk and dBASE. These scripting languages offer programming tools to a much wider audience because of their easier syntax, specialized built-in functionality, and minimal requirements for object creation.</p> + +<table class="standard-table"> + <caption>JavaScript comparado com Java</caption> + <thead> + <tr> + <th scope="col">JavaScript</th> + <th scope="col">Java</th> + </tr> + </thead> + <tbody> + <tr> + <td>Object-oriented. No distinction between types of objects. Inheritance is through the prototype mechanism, and properties and methods can be added to any object dynamically.</td> + <td>Class-based. Objects are divided into classes and instances with all inheritance through the class hierarchy. Classes and instances cannot have properties or methods added dynamically.</td> + </tr> + <tr> + <td>Variable data types are not declared (dynamic typing).</td> + <td>Variable data types must be declared (static typing).</td> + </tr> + <tr> + <td>Cannot automatically write to hard disk.</td> + <td>Can automatically write to hard disk.</td> + </tr> + </tbody> +</table> + +<p>For more information on the differences between JavaScript and Java, see the chapter <a href="/pt-PT/docs/Web/JavaScript/Guia/Detalhes_do_modelo_de_objeto">Details of the object model</a>.</p> + +<h2 id="JavaScript_and_the_ECMAScript_Specification" name="JavaScript_and_the_ECMAScript_Specification">JavaScript e a especificação ECMAScript</h2> + +<p>JavaScript is standardized at <a class="external" href="http://www.ecma-international.org/">Ecma International</a> — the European association for standardizing information and communication systems (ECMA was formerly an acronym for the European Computer Manufacturers Association) to deliver a standardized, international programming language based on JavaScript. This standardized version of JavaScript, called ECMAScript, behaves the same way in all applications that support the standard. Companies can use the open standard language to develop their implementation of JavaScript. The ECMAScript standard is documented in the ECMA-262 specification. See <a href="/en-US/docs/Web/JavaScript/New_in_JavaScript">New in JavaScript</a> to learn more about different versions of JavaScript and ECMAScript specification editions.</p> + +<p>The ECMA-262 standard is also approved by the <a class="external" href="http://www.iso.ch/">ISO</a> (International Organization for Standardization) as ISO-16262. You can also find the specification on <a class="external" href="http://www.ecma-international.org/publications/standards/Ecma-262.htm">the Ecma International website</a>. The ECMAScript specification does not describe the Document Object Model (DOM), which is standardized by the <a class="external" href="http://www.w3.org/">World Wide Web Consortium (W3C)</a> and/or <a href="https://whatwg.org">WHATWG (Web Hypertext Application Technology Working Group)</a>. The DOM defines the way in which HTML document objects are exposed to your script. To get a better idea about the different technologies that are used when programming with JavaScript, consult the article <a href="/en-US/docs/Web/JavaScript/JavaScript_technologies_overview">JavaScript technologies overview</a>.</p> + +<h3 id="JavaScript_Documentation_versus_the_ECMAScript_Specification" name="JavaScript_Documentation_versus_the_ECMAScript_Specification">Documentação JavaScript versus especificação ECMAScript</h3> + +<p>The ECMAScript specification is a set of requirements for implementing ECMAScript; it is useful if you want to implement standards-compliant language features in your ECMAScript implementation or engine (such as SpiderMonkey in Firefox, or v8 in Chrome).</p> + +<p>The ECMAScript document is not intended to help script programmers; use the JavaScript documentation for information on writing scripts.</p> + +<p>The ECMAScript specification uses terminology and syntax that may be unfamiliar to a JavaScript programmer. Although the description of the language may differ in ECMAScript, the language itself remains the same. JavaScript supports all functionality outlined in the ECMAScript specification.</p> + +<p>The JavaScript documentation describes aspects of the language that are appropriate for a JavaScript programmer.</p> + +<h2 id="Começar_com_JavaScript">Começar com JavaScript</h2> + +<p>Getting started with JavaScript is easy: all you need is a modern Web browser. This guide includes some JavaScript features which are only currently available in the latest versions of Firefox, so using the most recent version of Firefox is recommended.</p> + +<p>There are two tools built into Firefox that are useful for experimenting with JavaScript: the Web Console and Scratchpad.</p> + +<h3 id="A_Consola_da_Web">A Consola da Web</h3> + +<p>A <a href="/pt-PT/docs/Tools/Consola_da_Web">Consola da Web</a> shows you information about the currently loaded Web page, and also includes a <a href="/en-US/docs/Tools/Web_Console#The_command_line_interpreter">command line</a> that you can use to execute JavaScript expressions in the current page.</p> + +<p>To open the Web Console (Ctrl+Shift+K), select "Web Console" from the "Developer" menu, which is under the "Tools" menu in Firefox. It appears at the bottom of the browser window. Along the bottom of the console is a command line that you can use to enter JavaScript, and the output appears in the pane above:</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/7363/web-console-commandline.png" style="display: block; margin-left: auto; margin-right: auto;"></p> + +<h3 id="Scratchpad">Scratchpad</h3> + +<p>The Web Console is great for executing single lines of JavaScript, but although you can execute multiple lines, it's not very convenient for that, and you can't save your code samples using the Web Console. So for more complex examples <a href="/en-US/docs/Tools/Scratchpad">Scratchpad</a> is a better tool.</p> + +<p>To open Scratchpad (Shift+F4), select "Scratchpad" from the "Developer" menu, which is under the menu in Firefox. It opens in a separate window and is an editor that you can use to write and execute JavaScript in the browser. You can also save scripts to disk and load them from disk.</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/7365/scratchpad.png" style="display: block; margin-left: auto; margin-right: auto;"></p> + +<h3 id="Olá_mundo">Olá mundo</h3> + +<p>To get started with writing JavaScript, open the Scratchpad and write your first "Hello world" JavaScript code:</p> + +<pre class="brush: js">function greetMe(yourName) { + alert("Hello " + yourName); +} + +greetMe("World"); +</pre> + +<p>Select the code in the pad and hit Ctrl+R to watch it unfold in your browser!</p> + +<p>In the following pages, this guide will introduce you to the JavaScript syntax and language features, so that you will be able to write more complex applications.</p> + +<p>{{PreviousNext("Web/JavaScript/Guide", "Web/JavaScript/Guide/Grammar_and_types")}}</p> |