diff options
author | Florian Merz <me@fiji-flo.de> | 2021-02-11 14:50:24 +0100 |
---|---|---|
committer | Florian Merz <me@fiji-flo.de> | 2021-02-11 14:50:24 +0100 |
commit | 2c2df5ea01eb5cd8b9ea226b2869337e59c5fe3e (patch) | |
tree | 86ab4534d10092b293d4b7ab169fe1a8a2421bfa /files/pt-pt/web/javascript/guia | |
parent | 8260a606c143e6b55a467edf017a56bdcd6cba7e (diff) | |
download | translated-content-2c2df5ea01eb5cd8b9ea226b2869337e59c5fe3e.tar.gz translated-content-2c2df5ea01eb5cd8b9ea226b2869337e59c5fe3e.tar.bz2 translated-content-2c2df5ea01eb5cd8b9ea226b2869337e59c5fe3e.zip |
unslug pt-pt: move
Diffstat (limited to 'files/pt-pt/web/javascript/guia')
8 files changed, 0 insertions, 3228 deletions
diff --git a/files/pt-pt/web/javascript/guia/detalhes_do_modelo_de_objeto/index.html b/files/pt-pt/web/javascript/guia/detalhes_do_modelo_de_objeto/index.html deleted file mode 100644 index 01de143289..0000000000 --- a/files/pt-pt/web/javascript/guia/detalhes_do_modelo_de_objeto/index.html +++ /dev/null @@ -1,735 +0,0 @@ ---- -title: Detalhes do modelo de objeto -slug: Web/JavaScript/Guia/Detalhes_do_modelo_de_objeto -tags: - - Guia(2) - - Intermediário - - JavaScript - - Objeto -translation_of: Web/JavaScript/Guide/Details_of_the_Object_Model ---- -<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/guia/expressoes_e_operadores/index.html b/files/pt-pt/web/javascript/guia/expressoes_e_operadores/index.html deleted file mode 100644 index d0c815aac5..0000000000 --- a/files/pt-pt/web/javascript/guia/expressoes_e_operadores/index.html +++ /dev/null @@ -1,832 +0,0 @@ ---- -title: Expressoes e Operadores -slug: Web/JavaScript/Guia/Expressoes_e_Operadores ---- -<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Functions", "Web/JavaScript/Guide/Numbers_and_dates")}}</div> -<p><span id="result_box" lang="pt"><span class="hps">Este capítulo descreve</span> <span class="hps">expressões e operadores JavaScript</span><span>, incluindo </span></span>atribuição<span id="result_box" lang="pt"><span>, comparação,</span> <span class="hps">aritmética,</span> <span class="hps">bit a bit</span><span>, lógico, string</span><span>, e</span> <span class="hps">operadores especiais.</span></span></p> - -<h2 id="Expressões">Expressões</h2> - -<p>Uma <em>expressão</em> é qualquer unidade de código válida que resolve um valor.</p> - -<p><span id="result_box" lang="pt"><span class="alt-edited hps">Conceitualmente</span><span>, há dois</span> <span class="hps">tipos de expressões</span><span>: aqueles</span> <span class="hps">que</span> <span class="hps">atribui um valor</span> <span class="hps">para</span> <span class="hps">uma variável, e</span> <span class="hps">aqueles</span> <span class="hps">que</span> <span class="hps">simplesmente tem</span> <span class="hps">um valor.</span> <span class="hps">Por exemplo,</span> <span class="hps">a expressão</span> <code><span class="hps">x = 7</span></code> <span class="hps">é uma expressão que</span> <span class="hps">atribui</span> a x <span class="hps">o valor </span><span class="hps">sete.</span> <span class="hps">Esta expressão</span> <span class="hps">avalia</span><span>-se</span> <span class="hps">a sete.</span> <span class="hps">Tais expressões</span> <span class="alt-edited hps">usam <em>operadores de atribuição</em></span><span>.</span> <span class="hps">Por outro lado</span><span>, a expressão de</span> <code><span class="hps">3 + 4</span></code> <span class="hps">simplesmente avalia</span> <span class="hps">a sete</span><span>; ele</span> <span class="hps">não realiza</span> <span class="hps">uma atribuição.</span> <span class="hps">Os</span> <span class="hps">operadores usados</span> <span class="hps">em tais expressões</span> <span class="hps">são referidos</span> <span class="hps">simplesmente como</span> <span class="hps"><em>operadores</em>.</span></span></p> - -<p><span class="short_text" id="result_box" lang="pt"><span class="hps">JavaScript</span> <span class="hps">tem os seguintes tipos</span> <span class="hps">de expressões:</span></span></p> - -<ul> - <li><span id="result_box" lang="pt"><span class="hps">Aritmética:</span> <span class="hps">resulta em um número</span><span>, por exemplo</span> <span class="hps">3,14159.</span></span> (Generally uses {{ web.link("#Arithmetic_operators", "arithmetic operators") }}.)</li> - <li><span id="result_box" lang="pt"><span class="hps">String:</span> <span class="hps">avalia</span> <span class="hps">em</span> <span class="hps">uma cadeia de caracteres</span><span>, por exemplo,</span> <span class="hps">"Fred</span><span>" ou</span> <span class="hps">"234"</span></span>. (Generally uses {{ web.link("#String_operators", "string operators") }}.)</li> - <li>Logical: resulta em verdadeira (true em inglês) ou falsa (false em inglês). (Often involves {{ web.link("#Logical_operators", "logical operators") }}.)</li> - <li>Object: resulta como um objeto. (See {{ web.link("#Special_operators", "special operators") }} for various ones that evaluate to objects.)</li> -</ul> - -<h2 id="Operadores">Operadores</h2> - -<p><span id="result_box" lang="pt"><span class="hps">JavaScript</span> <span class="hps">tem os seguintes tipos</span> <span class="hps">de operadores.</span> <span class="hps">Esta seção</span> <span class="hps">descreve os operadores</span> <span class="hps">e contém informações sobre</span> <span class="hps">a precedência do operador</span><span>.</span></span></p> - -<ul> - <li>{{ web.link("#Assignment_operators", "Assignment operators") }}</li> - <li>{{ web.link("#Comparison_operators", "Comparison operators") }}</li> - <li>{{ web.link("#Arithmetic_operators", "Arithmetic operators") }}</li> - <li>{{ web.link("#Bitwise_operators", "Bitwise operators") }}</li> - <li>{{ web.link("#Logical_operators", "Logical operators") }}</li> - <li>{{ web.link("#String_operators", "String operators") }}</li> - <li>{{ web.link("#Special_operators", "Special operators") }}</li> -</ul> - -<p>JavaScript has both <em>binary</em> and <em>unary</em> operators, and one special ternary operator, the conditional operator. A binary operator requires two operands, one before the operator and one after the operator:</p> - -<pre><em>operand1</em> <em>operator</em> <em>operand2</em> -</pre> - -<p>For example, <code>3+4</code> or <code>x*y</code>.</p> - -<p>A unary operator requires a single operand, either before or after the operator:</p> - -<pre><em>operator</em> <em>operand</em> -</pre> - -<p>or</p> - -<pre><em>operand</em> <em>operator</em> -</pre> - -<p>For example, <code>x++</code> or <code>++x</code>.</p> - -<h3 id="Assignment_operators">Assignment operators</h3> - -<p>An assignment operator assigns a value to its left operand based on the value of its right operand. The basic assignment operator is equal (=), which assigns the value of its right operand to its left operand. That is, x = y assigns the value of y to x.</p> - -<p>The other assignment operators are shorthand for standard operations, as shown in the following table.</p> - -<table class="standard-table"> - <caption>Table 3.1 Assignment operators</caption> - <thead> - <tr> - <th scope="col">Shorthand operator</th> - <th scope="col">Meaning</th> - </tr> - </thead> - <tbody> - <tr> - <td><code>x += y</code></td> - <td><code>x = x + y</code></td> - </tr> - <tr> - <td><code>x -= y</code></td> - <td><code>x = x - y</code></td> - </tr> - <tr> - <td><code>x *= y</code></td> - <td><code>x = x * y</code></td> - </tr> - <tr> - <td><code>x /= y</code></td> - <td><code>x = x / y</code></td> - </tr> - <tr> - <td><code>x %= y</code></td> - <td><code>x = x % y</code></td> - </tr> - <tr> - <td><code>x <<= y</code></td> - <td><code>x = x << y</code></td> - </tr> - <tr> - <td><code>x >>= y</code></td> - <td><code>x = x >> y</code></td> - </tr> - <tr> - <td><code>x >>>= y</code></td> - <td><code>x = x >>> y</code></td> - </tr> - <tr> - <td><code>x &= y</code></td> - <td><code>x = x & y</code></td> - </tr> - <tr> - <td><code>x ^= y</code></td> - <td><code>x = x ^ y</code></td> - </tr> - <tr> - <td><code>x |= y</code></td> - <td><code>x = x | y</code></td> - </tr> - </tbody> -</table> - -<h3 id="Comparison_operators">Comparison operators</h3> - -<p><span class="comment">This seems to me kind of poorly explained, mostly the difference betwen "==" and "==="...</span> A comparison operator compares its operands and returns a logical value based on whether the comparison is true. The operands can be numerical, string, logical, or object values. Strings are compared based on standard lexicographical ordering, using Unicode values. In most cases, if the two operands are not of the same type, JavaScript attempts to convert the operands to an appropriate type for the comparison. (The sole exceptions to this rule are <code>===</code> and <code>!==</code>, which perform "strict" equality and inequality and which do not attempt to convert the operands to compatible types before checking equality.) This generally results in a numerical comparison being performed. The following table describes the comparison operators, assuming the following code:</p> - -<pre class="brush: js">var var1 = 3, var2 = 4; -</pre> - -<table class="standard-table"> - <caption>Table 3.2 Comparison operators</caption> - <thead> - <tr> - <th scope="col">Operator</th> - <th scope="col">Description</th> - <th scope="col">Examples returning true</th> - </tr> - </thead> - <tbody> - <tr> - <td>Equal (<code>==</code>)</td> - <td>Returns true if the operands are equal.</td> - <td><code>3 == var1</code> - <p><code>"3" == var1</code></p> - <code>3 == '3'</code></td> - </tr> - <tr> - <td>Not equal (<code>!=</code>)</td> - <td>Returns true if the operands are not equal.</td> - <td><code>var1 != 4<br> - var2 != "3"</code></td> - </tr> - <tr> - <td>Strict equal (<code>===</code>)</td> - <td>Returns true if the operands are equal and of the same type.</td> - <td><code>3 === var1</code></td> - </tr> - <tr> - <td>Strict not equal (<code>!==</code>)</td> - <td>Returns true if the operands are not equal and/or not of the same type.</td> - <td><code>var1 !== "3"<br> - 3 !== '3'</code></td> - </tr> - <tr> - <td>Greater than (<code>></code>)</td> - <td>Returns true if the left operand is greater than the right operand.</td> - <td><code>var2 > var1<br> - "12" > 2</code></td> - </tr> - <tr> - <td>Greater than or equal (<code>>=</code>)</td> - <td>Returns true if the left operand is greater than or equal to the right operand.</td> - <td><code>var2 >= var1<br> - var1 >= 3</code></td> - </tr> - <tr> - <td>Less than (<code><</code>)</td> - <td>Returns true if the left operand is less than the right operand.</td> - <td><code>var1 < var2<br> - "12" < "2"</code></td> - </tr> - <tr> - <td>Less than or equal (<code><=</code>)</td> - <td>Returns true if the left operand is less than or equal to the right operand.</td> - <td><code>var1 <= var2<br> - var2 <= 5</code></td> - </tr> - </tbody> -</table> - -<h3 id="Arithmetic_operators">Arithmetic operators</h3> - -<p>Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value. The standard arithmetic operators are addition (+), subtraction (-), multiplication (*), and division (/). These operators work as they do in most other programming languages when used with floating point numbers (in particular, note that division by zero produces <a href="/en-US/docs/JavaScript/Reference/Global_Objects/NaN" title="en-US/docs/JavaScript/Reference/Global_Properties/NaN"><code>NaN</code></a>). For example:</p> - -<pre class="brush: js">console.log(1 / 2); /* prints 0.5 */ -console.log(1 / 2 == 1.0 / 2.0); /* also this is true */ -</pre> - -<p>In addition, JavaScript provides the arithmetic operators listed in the following table.</p> - -<table class="fullwidth-table"> - <caption>Table 3.3 Arithmetic operators</caption> - <thead> - <tr> - <th scope="col">Operator</th> - <th scope="col">Description</th> - <th scope="col">Example</th> - </tr> - </thead> - <tbody> - <tr> - <td><code>%</code><br> - (Modulus)</td> - <td>Binary operator. Returns the integer remainder of dividing the two operands.</td> - <td>12 % 5 returns 2.</td> - </tr> - <tr> - <td><code>++</code><br> - (Increment)</td> - <td>Unary operator. Adds one to its operand. If used as a prefix operator (<code>++x</code>), returns the value of its operand after adding one; if used as a postfix operator (<code>x++</code>), returns the value of its operand before adding one.</td> - <td>If <code>x</code> is 3, then <code>++x</code> sets <code>x</code> to 4 and returns 4, whereas <code>x++</code> returns 3 and, only then, sets <code>x</code> to 4.</td> - </tr> - <tr> - <td><code>--</code><br> - (Decrement)</td> - <td>Unary operator. Subtracts one from its operand. The return value is analogous to that for the increment operator.</td> - <td>If <code>x</code> is 3, then <code>--x</code> sets <code>x</code> to 2 and returns 2, whereas <code>x--</code> returns 3 and, only then, sets <code>x</code> to 2.</td> - </tr> - <tr> - <td><code>-</code><br> - (Unary negation)</td> - <td>Unary operator. Returns the negation of its operand.</td> - <td>If <code>x</code> is 3, then <code>-x</code> returns -3.</td> - </tr> - </tbody> -</table> - -<h3 id="Bitwise_operators">Bitwise operators</h3> - -<p>Bitwise operators treat their operands as a set of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.</p> - -<p>The following table summarizes JavaScript's bitwise operators.</p> - -<table class="standard-table"> - <caption>Table 3.4 Bitwise operators</caption> - <thead> - <tr> - <th scope="col">Operator</th> - <th scope="col">Usage</th> - <th scope="col">Description</th> - </tr> - </thead> - <tbody> - <tr> - <td>Bitwise AND</td> - <td><code>a & b</code></td> - <td>Returns a one in each bit position for which the corresponding bits of both operands are ones.</td> - </tr> - <tr> - <td>Bitwise OR</td> - <td><code>a | b</code></td> - <td>Returns a one in each bit position for which the corresponding bits of either or both operands are ones.</td> - </tr> - <tr> - <td>Bitwise XOR</td> - <td><code>a ^ b</code></td> - <td>Returns a one in each bit position for which the corresponding bits of either but not both operands are ones.</td> - </tr> - <tr> - <td>Bitwise NOT</td> - <td><code>~ a</code></td> - <td>Inverts the bits of its operand.</td> - </tr> - <tr> - <td>Left shift</td> - <td><code>a << b</code></td> - <td>Shifts <code>a</code> in binary representation <code>b</code> bits to the left, shifting in zeros from the right.</td> - </tr> - <tr> - <td>Sign-propagating right shift</td> - <td><code>a >> b</code></td> - <td>Shifts <code>a</code> in binary representation <code>b</code> bits to the right, discarding bits shifted off.</td> - </tr> - <tr> - <td>Zero-fill right shift</td> - <td><code>a >>> b</code></td> - <td>Shifts <code>a</code> in binary representation <code>b</code> bits to the right, discarding bits shifted off, and shifting in zeros from the left.</td> - </tr> - </tbody> -</table> - -<h4 id="Bitwise_Logical_Operators" name="Bitwise_Logical_Operators">Bitwise logical operators</h4> - -<p>Conceptually, the bitwise logical operators work as follows:</p> - -<ul> - <li>The operands are converted to thirty-two-bit integers and expressed by a series of bits (zeros and ones).</li> - <li>Each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on.</li> - <li>The operator is applied to each pair of bits, and the result is constructed bitwise.</li> -</ul> - -<p>For example, the binary representation of nine is 1001, and the binary representation of fifteen is 1111. So, when the bitwise operators are applied to these values, the results are as follows:</p> - -<table class="standard-table"> - <caption>Table 3.5 Bitwise operator examples</caption> - <thead> - <tr> - <th scope="col">Expression</th> - <th scope="col">Result</th> - <th scope="col">Binary Description</th> - </tr> - </thead> - <tbody> - <tr> - <td><code>15 & 9</code></td> - <td><code>9</code></td> - <td><code>1111 & 1001 = 1001</code></td> - </tr> - <tr> - <td><code>15 | 9</code></td> - <td><code>15</code></td> - <td><code>1111 | 1001 = 1111</code></td> - </tr> - <tr> - <td><code>15 ^ 9</code></td> - <td><code>6</code></td> - <td><code>1111 ^ 1001 = 0110</code></td> - </tr> - <tr> - <td><code>~15</code></td> - <td><code>0</code></td> - <td><code>~1111 = 0000</code></td> - </tr> - <tr> - <td><code>~9</code></td> - <td><code>6</code></td> - <td><code>~1001 = 0110</code></td> - </tr> - </tbody> -</table> - -<p> </p> - -<h4 id="Bitwise_Shift_Operators" name="Bitwise_Shift_Operators">Bitwise shift operators</h4> - -<p>The bitwise shift operators take two operands: the first is a quantity to be shifted, and the second specifies the number of bit positions by which the first operand is to be shifted. The direction of the shift operation is controlled by the operator used.</p> - -<p>Shift operators convert their operands to thirty-two-bit integers and return a result of the same type as the left operand.</p> - -<p>The shift operators are listed in the following table.</p> - -<table class="fullwidth-table"> - <caption>Table 3.6 Bitwise shift operators</caption> - <thead> - <tr> - <th scope="col">Operator</th> - <th scope="col">Description</th> - <th scope="col">Example</th> - </tr> - </thead> - <tbody> - <tr> - <td><code><<</code><br> - (Left shift)</td> - <td>This operator shifts the first operand the specified number of bits to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right.</td> - <td><code>9<<2</code> yields 36, because 1001 shifted 2 bits to the left becomes 100100, which is 36.</td> - </tr> - <tr> - <td><code>>></code><br> - (Sign-propagating right shift)</td> - <td>This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Copies of the leftmost bit are shifted in from the left.</td> - <td><code>9>>2</code> yields 2, because 1001 shifted 2 bits to the right becomes 10, which is 2. Likewise, <code>-9>>2</code> yields -3, because the sign is preserved.</td> - </tr> - <tr> - <td><code>>>></code><br> - (Zero-fill right shift)</td> - <td>This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left.</td> - <td><code>19>>>2</code> yields 4, because 10011 shifted 2 bits to the right becomes 100, which is 4. For non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result.</td> - </tr> - </tbody> -</table> - -<h3 id="Logical_operators">Logical operators</h3> - -<p>Logical operators are typically used with Boolean (logical) values; when they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value. The logical operators are described in the following table.</p> - -<table class="fullwidth-table"> - <caption>Table 3.6 Logical operators</caption> - <thead> - <tr> - <th scope="col">Operator</th> - <th scope="col">Usage</th> - <th scope="col">Description</th> - </tr> - </thead> - <tbody> - <tr> - <td><code>&&</code></td> - <td><code>expr1 && expr2</code></td> - <td>(Logical AND) Returns <code>expr1</code> if it can be converted to false; otherwise, returns <code>expr2</code>. Thus, when used with Boolean values, <code>&&</code> returns true if both operands are true; otherwise, returns false.</td> - </tr> - <tr> - <td><code>||</code></td> - <td><code>expr1 || expr2</code></td> - <td>(Logical OR) Returns <code>expr1</code> if it can be converted to true; otherwise, returns <code>expr2</code>. Thus, when used with Boolean values, <code>||</code> returns true if either operand is true; if both are false, returns false.</td> - </tr> - <tr> - <td><code>!</code></td> - <td><code>!expr</code></td> - <td>(Logical NOT) Returns false if its single operand can be converted to true; otherwise, returns true.</td> - </tr> - </tbody> -</table> - -<p>Examples of expressions that can be converted to false are those that evaluate to null, 0, the empty string (""), or undefined.</p> - -<p>The following code shows examples of the && (logical AND) operator.</p> - -<pre class="brush: js">var a1 = true && true; // t && t returns true -var a2 = true && false; // t && f returns false -var a3 = false && true; // f && t returns false -var a4 = false && (3 == 4); // f && f returns false -var a5 = "Cat" && "Dog"; // t && t returns Dog -var a6 = false && "Cat"; // f && t returns false -var a7 = "Cat" && false; // t && f returns false -</pre> - -<p>The following code shows examples of the || (logical OR) operator.</p> - -<pre class="brush: js">var o1 = true || true; // t || t returns true -var o2 = false || true; // f || t returns true -var o3 = true || false; // t || f returns true -var o4 = false || (3 == 4); // f || f returns false -var o5 = "Cat" || "Dog"; // t || t returns Cat -var o6 = false || "Cat"; // f || t returns Cat -var o7 = "Cat" || false; // t || f returns Cat -</pre> - -<p>The following code shows examples of the ! (logical NOT) operator.</p> - -<pre class="brush: js">var n1 = !true; // !t returns false -var n2 = !false; // !f returns true -var n3 = !"Cat"; // !t returns false -</pre> - -<h4 id="Short-Circuit_Evaluation" name="Short-Circuit_Evaluation">Short-circuit evaluation</h4> - -<p>As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:</p> - -<ul> - <li><code>false</code> && <em>anything</em> is short-circuit evaluated to false.</li> - <li><code>true</code> || <em>anything</em> is short-circuit evaluated to true.</li> -</ul> - -<p>The rules of logic guarantee that these evaluations are always correct. Note that the <em>anything</em> part of the above expressions is not evaluated, so any side effects of doing so do not take effect.</p> - -<h3 id="String_operators">String operators</h3> - -<p>In addition to the comparison operators, which can be used on string values, the concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings. For example, <code>"my " + "string"</code> returns the string <code>"my string"</code>.</p> - -<p>The shorthand assignment operator += can also be used to concatenate strings. For example, if the variable <code>mystring</code> has the value "alpha", then the expression <code>mystring += "bet"</code> evaluates to "alphabet" and assigns this value to <code>mystring</code>.</p> - -<h3 id="Special_operators">Special operators</h3> - -<p>JavaScript provides the following special operators:</p> - -<ul> - <li>{{ web.link("#Conditional_operator", "Conditional operator") }}</li> - <li>{{ web.link("#Comma_operator", "Comma operator") }}</li> - <li><code>{{ web.link("#delete", "delete") }}</code></li> - <li><code>{{ web.link("#in", "in") }}</code></li> - <li><code>{{ web.link("#instanceof", "instanceof") }}</code></li> - <li><code>{{ web.link("#new", "new") }}</code></li> - <li><code>{{ web.link("#this", "this") }}</code></li> - <li><code>{{ web.link("#typeof", "typeof") }}</code></li> - <li><code>{{ web.link("#void", "void") }}</code></li> -</ul> - -<h4 id="conditional_operator" name="conditional_operator">Conditional operator</h4> - -<p>The conditional operator is the only JavaScript operator that takes three operands. The operator can have one of two values based on a condition. The syntax is:</p> - -<pre><em>condition</em> ? <em>val1</em> : <em>val2</em> -</pre> - -<p>If <code>condition</code> is true, the operator has the value of <code>val1</code>. Otherwise it has the value of <code>val2</code>. You can use the conditional operator anywhere you would use a standard operator.</p> - -<p>For example,</p> - -<pre class="brush: js">var status = (age >= 18) ? "adult" : "minor"; -</pre> - -<p>This statement assigns the value "adult" to the variable <code>status</code> if <code>age</code> is eighteen or more. Otherwise, it assigns the value "minor" to <code>status</code>.</p> - -<h4 id="comma_operator" name="comma_operator">Comma operator</h4> - -<p>The comma operator (<code>,</code>) simply evaluates both of its operands and returns the value of the second operand. This operator is primarily used inside a <code>for</code> loop, to allow multiple variables to be updated each time through the loop.</p> - -<p>For example, if <code>a</code> is a 2-dimensional array with 10 elements on a side, the following code uses the comma operator to increment two variables at once. The code prints the values of the diagonal elements in the array:</p> - -<pre class="brush: js">for (var i = 0, j = 9; i <= 9; i++, j--) - document.writeln("a[" + i + "][" + j + "]= " + a[i][j]); -</pre> - -<h4 id="delete" name="delete"><code>delete</code></h4> - -<p>The <code>delete</code> operator deletes an object, an object's property, or an element at a specified index in an array. The syntax is:</p> - -<pre class="brush: js">delete objectName; -delete objectName.property; -delete objectName[index]; -delete property; // legal only within a with statement -</pre> - -<p>where <code>objectName</code> is the name of an object, <code>property</code> is an existing property, and <code>index</code> is an integer representing the location of an element in an array.</p> - -<p>The fourth form is legal only within a <code>with</code> statement, to delete a property from an object.</p> - -<p>You can use the <code>delete</code> operator to delete variables declared implicitly but not those declared with the <code>var</code> statement.</p> - -<p>If the <code>delete</code> operator succeeds, it sets the property or element to <code>undefined</code>. The <code>delete</code> operator returns true if the operation is possible; it returns false if the operation is not possible.</p> - -<pre class="brush: js">x = 42; -var y = 43; -myobj = new Number(); -myobj.h = 4; // create property h -delete x; // returns true (can delete if declared implicitly) -delete y; // returns false (cannot delete if declared with var) -delete Math.PI; // returns false (cannot delete predefined properties) -delete myobj.h; // returns true (can delete user-defined properties) -delete myobj; // returns true (can delete if declared implicitly) -</pre> - -<h5 id="Deleting_array_elements">Deleting array elements</h5> - -<p>When you delete an array element, the array length is not affected. For example, if you delete <code>a[3]</code>, <code>a[4]</code> is still <code>a[4]</code> and <code>a[3]</code> is undefined.</p> - -<p>When the <code>delete</code> operator removes an array element, that element is no longer in the array. In the following example, <code>trees[3]</code> is removed with <code>delete</code>. However, <code>trees[3]</code> is still addressable and returns <code>undefined</code>.</p> - -<pre class="brush: js">var trees = new Array("redwood", "bay", "cedar", "oak", "maple"); -delete trees[3]; -if (3 in trees) { - // this does not get executed -} -</pre> - -<p>If you want an array element to exist but have an undefined value, use the <code>undefined</code> keyword instead of the <code>delete</code> operator. In the following example, <code>trees[3]</code> is assigned the value <code>undefined</code>, but the array element still exists:</p> - -<pre class="brush: js">var trees = new Array("redwood", "bay", "cedar", "oak", "maple"); -trees[3] = undefined; -if (3 in trees) { - // this gets executed -} -</pre> - -<h4 id="in" name="in"><code>in</code></h4> - -<p>The <code>in</code> operator returns true if the specified property is in the specified object. The syntax is:</p> - -<pre class="brush: js">propNameOrNumber in objectName -</pre> - -<p>where <code>propNameOrNumber</code> is a string or numeric expression representing a property name or array index, and <code>objectName</code> is the name of an object.</p> - -<p>The following examples show some uses of the <code>in</code> operator.</p> - -<pre class="brush: js">// Arrays -var trees = new Array("redwood", "bay", "cedar", "oak", "maple"); -0 in trees; // returns true -3 in trees; // returns true -6 in trees; // returns false -"bay" in trees; // returns false (you must specify the index number, - // not the value at that index) -"length" in trees; // returns true (length is an Array property) - -// Predefined objects -"PI" in Math; // returns true -var myString = new String("coral"); -"length" in myString; // returns true - -// Custom objects -var mycar = {make: "Honda", model: "Accord", year: 1998}; -"make" in mycar; // returns true -"model" in mycar; // returns true -</pre> - -<h4 id="instanceof" name="instanceof"><code>instanceof</code></h4> - -<p>The <code>instanceof</code> operator returns true if the specified object is of the specified object type. The syntax is:</p> - -<pre class="brush: js">objectName instanceof objectType -</pre> - -<p>where <code>objectName</code> is the name of the object to compare to <code>objectType</code>, and <code>objectType</code> is an object type, such as <code>Date</code> or <code>Array</code>.</p> - -<p>Use <code>instanceof</code> when you need to confirm the type of an object at runtime. For example, when catching exceptions, you can branch to different exception-handling code depending on the type of exception thrown.</p> - -<p>For example, the following code uses <code>instanceof</code> to determine whether <code>theDay</code> is a <code>Date</code> object. Because <code>theDay</code> is a <code>Date</code> object, the statements in the <code>if</code> statement execute.</p> - -<pre class="brush: js">var theDay = new Date(1995, 12, 17); -if (theDay instanceof Date) { - // statements to execute -} -</pre> - -<h4 id="new" name="new"><code>new</code></h4> - -<p>You can use the <code>new</code> operator to create an instance of a user-defined object type or of one of the predefined object types <code>Array</code>, <code>Boolean</code>, <code>Date</code>, <code>Function</code>, <code>Image</code>, <code>Number</code>, <code>Object</code>, <code>Option</code>, <code>RegExp</code>, or <code>String</code>. On the server, you can also use it with <code>DbPool</code>, <code>Lock</code>, <code>File</code>, or <code>SendMail</code>. Use <code>new</code> as follows:</p> - -<pre class="brush: js">var objectName = new objectType([param1, param2, ..., paramN]); -</pre> - -<p>You can also create objects using object initializers, as described in {{ web.link("Working_with_objects#Using_object_initializers", "using object initializers") }}.</p> - -<p>See the <a href="/en-US/docs/JavaScript/Reference/Operators/new" title="en-US/docs/JavaScript/Reference/Operators/Special_Operators/new_Operator"><code>new</code> operator</a> page in the Core JavaScript Reference for more information.</p> - -<h4 id="this" name="this"><code>this</code></h4> - -<p>Use the <code>this</code> keyword to refer to the current object. In general, <code>this</code> refers to the calling object in a method. Use <code>this</code> as follows:</p> - -<pre class="brush: js">this["propertyName"] -</pre> - -<pre class="brush: js">this.propertyName -</pre> - -<p><strong>Example 1.</strong><br> - Suppose a function called <code>validate</code> validates an object's <code>value</code> property, given the object and the high and low values:</p> - -<pre class="brush: js">function validate(obj, lowval, hival){ - if ((obj.value < lowval) || (obj.value > hival)) - alert("Invalid Value!"); -} -</pre> - -<p>You could call <code>validate</code> in each form element's <code>onChange</code> event handler, using <code>this</code> to pass it the form element, as in the following example:</p> - -<pre class="brush: html"><B>Enter a number between 18 and 99:</B> -<INPUT TYPE="text" NAME="age" SIZE=3 - onChange="validate(this, 18, 99);"> -</pre> - -<p><strong>Example 2.</strong><br> - When combined with the <code>form</code> property, <code>this</code> can refer to the current object's parent form. In the following example, the form <code>myForm</code> contains a <code>Text</code> object and a button. When the user clicks the button, the value of the <code>Text</code> object is set to the form's name. The button's <code>onClick</code> event handler uses <code>this.form</code> to refer to the parent form, <code>myForm</code>.</p> - -<pre class="brush: html"><FORM NAME="myForm"> -Form name:<INPUT TYPE="text" NAME="text1" VALUE="Beluga"> -<P> -<INPUT NAME="button1" TYPE="button" VALUE="Show Form Name" - onClick="this.form.text1.value = this.form.name;"> -</FORM> -</pre> - -<h4 id="typeof" name="typeof"><code>typeof</code></h4> - -<p>The <code>typeof</code> operator is used in either of the following ways:</p> - -<ol> - <li> - <pre class="brush: js">typeof operand -</pre> - </li> - <li> - <pre class="brush: js">typeof (operand) -</pre> - </li> -</ol> - -<p>The <code>typeof</code> operator returns a string indicating the type of the unevaluated operand. <code>operand</code> is the string, variable, keyword, or object for which the type is to be returned. The parentheses are optional.</p> - -<p>Suppose you define the following variables:</p> - -<pre class="brush: js">var myFun = new Function("5 + 2"); -var shape = "round"; -var size = 1; -var today = new Date(); -</pre> - -<p>The <code>typeof</code> operator returns the following results for these variables:</p> - -<pre class="brush: js">typeof myFun; // returns "function" -typeof shape; // returns "string" -typeof size; // returns "number" -typeof today; // returns "object" -typeof dontExist; // returns "undefined" -</pre> - -<p>For the keywords <code>true</code> and <code>null</code>, the <code>typeof</code> operator returns the following results:</p> - -<pre class="brush: js">typeof true; // returns "boolean" -typeof null; // returns "object" -</pre> - -<p>For a number or string, the <code>typeof</code> operator returns the following results:</p> - -<pre class="brush: js">typeof 62; // returns "number" -typeof 'Hello world'; // returns "string" -</pre> - -<p>For property values, the <code>typeof</code> operator returns the type of value the property contains:</p> - -<pre class="brush: js">typeof document.lastModified; // returns "string" -typeof window.length; // returns "number" -typeof Math.LN2; // returns "number" -</pre> - -<p>For methods and functions, the <code>typeof</code> operator returns results as follows:</p> - -<pre class="brush: js">typeof blur; // returns "function" -typeof eval; // returns "function" -typeof parseInt; // returns "function" -typeof shape.split; // returns "function" -</pre> - -<p>For predefined objects, the <code>typeof</code> operator returns results as follows:</p> - -<pre class="brush: js">typeof Date; // returns "function" -typeof Function; // returns "function" -typeof Math; // returns "object" -typeof Option; // returns "function" -typeof String; // returns "function" -</pre> - -<h4 id="void" name="void"><code>void</code></h4> - -<p>The <code>void</code> operator is used in either of the following ways:</p> - -<ol> - <li> - <pre class="brush: js">void (expression) -</pre> - </li> - <li> - <pre class="brush: js">void expression -</pre> - </li> -</ol> - -<p>The <code>void</code> operator specifies an expression to be evaluated without returning a value. <code>expression</code> is a JavaScript expression to evaluate. The parentheses surrounding the expression are optional, but it is good style to use them.</p> - -<p>You can use the <code>void</code> operator to specify an expression as a hypertext link. The expression is evaluated but is not loaded in place of the current document.</p> - -<p>The following code creates a hypertext link that does nothing when the user clicks it. When the user clicks the link, <code>void(0)</code> evaluates to undefined, which has no effect in JavaScript.</p> - -<pre class="brush: html"><A HREF="javascript:void(0)">Click here to do nothing</A> -</pre> - -<p>The following code creates a hypertext link that submits a form when the user clicks it.</p> - -<pre class="brush: html"><A HREF="javascript:void(document.form.submit())"> -Click here to submit</A></pre> - -<h3 id="Operator_precedence">Operator precedence</h3> - -<p>The <em>precedence</em> of operators determines the order they are applied when evaluating an expression. You can override operator precedence by using parentheses.</p> - -<p>The following table describes the precedence of operators, from highest to lowest.</p> - -<p><small><em>In accordance with <a href="/en-US/docs/Talk:JavaScript/Guide/Obsolete_Pages/Operators#Precedence_Tablerators#Precedence_Table" title="Talk:JavaScript/Guide/Obsolete_Pages/Operators#Precedence_Table">relevant discussion</a>, this table was reversed to list operators in <strong>decreasing</strong> order of priority.</em></small></p> - -<table class="standard-table"> - <caption>Table 3.7 Operator precedence</caption> - <thead> - <tr> - <th scope="col">Operator type</th> - <th scope="col">Individual operators</th> - </tr> - </thead> - <tbody> - <tr> - <td>member</td> - <td><code>. []</code></td> - </tr> - <tr> - <td>call / create instance</td> - <td><code>() new</code></td> - </tr> - <tr> - <td>negation/increment</td> - <td><code>! ~ - + ++ -- typeof void delete</code></td> - </tr> - <tr> - <td>multiply/divide</td> - <td><code>* / %</code></td> - </tr> - <tr> - <td>addition/subtraction</td> - <td><code>+ -</code></td> - </tr> - <tr> - <td>bitwise shift</td> - <td><code><< >> >>></code></td> - </tr> - <tr> - <td>relational</td> - <td><code>< <= > >= in instanceof</code></td> - </tr> - <tr> - <td>equality</td> - <td><code>== != === !==</code></td> - </tr> - <tr> - <td>bitwise-and</td> - <td><code>&</code></td> - </tr> - <tr> - <td>bitwise-xor</td> - <td><code>^</code></td> - </tr> - <tr> - <td>bitwise-or</td> - <td><code>|</code></td> - </tr> - <tr> - <td>logical-and</td> - <td><code>&&</code></td> - </tr> - <tr> - <td>logical-or</td> - <td><code>||</code></td> - </tr> - <tr> - <td>conditional</td> - <td><code>?:</code></td> - </tr> - <tr> - <td>assignment</td> - <td><code>= += -= *= /= %= <<= >>= >>>= &= ^= |=</code></td> - </tr> - <tr> - <td>comma</td> - <td><code>,</code></td> - </tr> - </tbody> -</table> - -<p>A more detailed version of this table, complete with links to additional details about each operator, may be found in <a href="/en-US/docs/JavaScript/Reference/Operators/Operator_Precedence#Table" title="en-US/docs/JavaScript/Reference/Operators/Operator_Precedence#Table">JavaScript Reference</a>.</p> diff --git a/files/pt-pt/web/javascript/guia/gramática_e_tipos/index.html b/files/pt-pt/web/javascript/guia/gramática_e_tipos/index.html deleted file mode 100644 index 109bd99fe4..0000000000 --- a/files/pt-pt/web/javascript/guia/gramática_e_tipos/index.html +++ /dev/null @@ -1,641 +0,0 @@ ---- -title: Gramática e tipos -slug: Web/JavaScript/Guia/Gramática_e_tipos -tags: - - Guia(2) - - JavaScript -translation_of: Web/JavaScript/Guide/Grammar_and_types ---- -<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/guia/index.html b/files/pt-pt/web/javascript/guia/index.html deleted file mode 100644 index aec08fb7ad..0000000000 --- a/files/pt-pt/web/javascript/guia/index.html +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: Guia de JavaScript -slug: Web/JavaScript/Guia -tags: - - Guía - - JavaScript - - 'l10n:prioridade' -translation_of: Web/JavaScript/Guide ---- -<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/guia/introdução/index.html b/files/pt-pt/web/javascript/guia/introdução/index.html deleted file mode 100644 index f77bb74379..0000000000 --- a/files/pt-pt/web/javascript/guia/introdução/index.html +++ /dev/null @@ -1,137 +0,0 @@ ---- -title: Introdução -slug: Web/JavaScript/Guia/Introdução -tags: - - Guía - - JavaScript -translation_of: Web/JavaScript/Guide/Introduction ---- -<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> diff --git a/files/pt-pt/web/javascript/guia/introdução_ao_javascript/index.html b/files/pt-pt/web/javascript/guia/introdução_ao_javascript/index.html deleted file mode 100644 index 549ecbe331..0000000000 --- a/files/pt-pt/web/javascript/guia/introdução_ao_javascript/index.html +++ /dev/null @@ -1,47 +0,0 @@ ---- -title: Introdução ao JavaScript -slug: Web/JavaScript/Guia/Introdução_ao_JavaScript ---- -<p>Este capítulo introduz o JavaScript e discute alguns de seus conceitos fundamentais.</p> -<h3 id="What_is_JavaScript.3F" name="What_is_JavaScript.3F">O que é o JavaScript?</h3> -<p>O JavaScript é uma linguagem de script multiplataforma, orientada a objetos. O JavaScript é uma linguagem pequena e leve; não é útil como uma linguagem de uso isolado, mas é projetada para fácil integração em outros produtos e aplicações, tais como navegadores web. Dentro de um ambiente de hospedagem, o JavaScript pode ser conectado aos objetos de seu ambiente para proporcionar um controle programático sobre elas.</p> -<p>O núcleo do JavaScript contém um núcleo de objetos, como <code>Array</code>, <code>Date</code>, e <code>Math</code>, e um núcleo de elementos de linguagem como operadores, estruturas de controle, e declarações. O núcleo do JavaScript pode ser extendido para uma variedade de propósitos complementando-o com objetos adicionais; por exemplo:</p> -<ul> <li><em>O lado do cliente no JavaScript</em> extende o núcleo da linguagem fornecendo objetos para controlar um navegador (Navigator ou outro navegador web) e seu Document Object Model (DOM). Por exemplo, extensões para o lado do cliente permitem a uma aplicação colocar elementos em um formulário HTML e responder a eventos de usuários como cliques de mouse, entrada de dados e navegação na página.</li> <li><em>O lado do servidor no JavaScript</em> extende o núcleo da linguagem fornecendo objetos relevantes à execução de JavaScript no servidor. Por exemplo, extensões do lado do servidor permitem a uma aplicação comunicar-se com um banco de dados relacional, proporcionar continuidade de informação de uma invocação da aplicação para outra, ou executar manipulações de arquivos em um servidor.</li> -</ul> -<p>Através da funcionalidade JavaScript's LiveConnect, pode-se permitir que códigos em Java e em JavaScript comuniquem-se. É possível instanciar objetos Java e acessar seus métodos e campos públicos a partir do JavaScript. A partir do Java, por sua vez, pode-se acessar objetos, propriedades e métodos do JavaScript.</p> -<p>O Netscape inventou o JavaScript e o JavaScript foi inicialmente usado em navegadores Netscape.</p> -<h3 id="JavaScript_and_Java" name="JavaScript_and_Java">JavaScript e Java</h3> -<p>O JavaScript e o Java são similares em algumas coisas, mas fundamentalmente diferentes em outras. A linguagem JavaScript assemelha-se ao Java, mas não possui a checagem de tipos forte e digitação estática do Java. O JavaScript suport a maioria das sintaxes de expressões em Java e um construtor básico de controles de fluxo.</p> -<p>Em contraste com o sistema em tempo de compilação do Java, de classes construídas por declarações, o JavaScript suporta um sistema de tempo de execução baseado em um pequeno número de tipos de dados representando números, booleanos, e valores de strings. O JavaScript possui um modelo de objetos baseado em protótipos, ao invés do mais comum, modelo de objetos baseado em classes. O modelo baseado em protótipos provê a herança dinâmica; isto é, o que é herdado pode variar para objetos individuais. O JavaScript também suporta funções sem requisições especiais de declaração. Funções podem ser propriedades de objetos, executando métodos fracamente tipados.</p> -<p>O JavaScript é uma linguagem com forma bastante livre comparada ao Java. Você não precisa declarar todas as variáveis, classes e métodos. Você não precisa se preocupar se os métodos são públicos, privados ou protegidos, e você não precisa implementar interfaces. Tipos de variáveis, parâmetros e retornos de funções não são explicitados.</p> -<p>O Java é uma linguagem de programação baseada em classes e projetava para rápida execução e tipagem segura. Tipagem segura significa, por exemplo, que você não pode converter um inteiro do Java para uma referência de um objeto ou acessar a memória privada, corrompendo bytecodes do Java. O modelo baseado em classes do Java significa que o programa consiste exclusivamente de classes e seus métodos. A herança das classes no Java e a tipagem forte, geralmente requerem objetos com hierarquias firmemente acopladas. Estes requisitos fazem do Java uma linguagem de programação mais complexa que a autoria do JavaScript.</p> -<p>Em contraste, o JavaScript descende em espírito de uma linha menor, linguagens tipadas dinamicamente, tais como HyperTalk e dBASE. Estas linguagens de stript oferecem ferramentas de programação para um público muito maior, devido a simplicidade de sua sintaxe, funcionalidades especializadas integradas e requisitos mínimos para criação de objetos.</p> -<table class="standard-table"> <caption>Tabela 1.1 JavaScript em comparação ao Java</caption> <thead> <tr> <th scope="col">JavaScript</th> <th scope="col">Java</th> </tr> </thead> <tbody> <tr> <td>Orientação a objetos. Sem distinção entre tipos de objetos. A herança ocorre através do mecanismo de protótipos e os métodos e propriedades podem ser adicionados a qualquer objeto dinamicamente.</td> <td>Baseada em classes. Objetos são divididos em classes e instâncias com toda a herança através da hierarquia da classe. Classes e instâncias não podem ter métodos e propriedades adicionados dinamicamente.</td> </tr> <tr> <td>Tipos de dados variáveis não são declarados (tipagem dinâmica).</td> <td>Tipos de dados variáveis precisam ser declarados (tipagem estática).</td> </tr> <tr> <td>Não pode escrever automaticamente no disco rígido.</td> <td>Não pode escrever automaticamente no disco rígido.</td> </tr> </tbody> -</table> -<p>Para mais informações sobre as diferenças entre o JavaScript e o Java, veja o capítulo <a href="/en/JavaScript/Guide/Details_of_the_Object_Model" title="en/JavaScript/Guide/Details of the Object Model">Details of the Object Model</a>.</p><h3 id="JavaScript_and_the_ECMAScript_Specification" name="JavaScript_and_the_ECMAScript_Specification">JavaScript e a especificação ECMAScript</h3> -<p>O Netscape inventou o JavaScript e o JavaScript foi primeiramente usado nos navegadores Netscape. Entretanto, a Netscape está trabalhando com a <a class="external" href="http://www.ecma-international.org/">Ecma International</a> — a associação européia para padronizão de informação e sistemas de comunicação (formalmente conhecida como ECMA - European Computer Manufacturers Association, em português: Associação de Fabricantes de Computadores Europeus) — para entregar uma linguagem de programação internacional padronizada, baseada no JavaScript. Esta versão padronizada do JavaScript, chamada de ECMAScript, comporta-se da mesma maneira em todas as aplicações que suportem o padrão. Empresas podem usar a linguagem padrão aberta para desenvolver sua implementação do JavaScript. O ECMAScript padrão é documentado na especificação ECMA-262.</p> -<p>O padrão ECMA-262 é também aprovado pela <a class="external" href="http://www.iso.ch/">ISO</a> (International Organization for Standardization, em português: Organização Internacional para Padronização) como ISO-16262. Você pode encontrar uma <a class="external" href="http://www.mozilla.org/js/language/E262-3.pdf">versão PDF do ECMA-262</a> (en) no site da Mozilla. Você pode também encontrar a especificação em <a class="external" href="http://www.ecma-international.org/publications/standards/Ecma-262.htm">the Ecma International website</a> (en). A especificação do ECMAScript não descreve o Document Object Model (DOM), o qual é padronizado pelo <a class="external" href="http://www.w3.org/">World Wide Web Consortium (W3C)</a>. O DOM define a maneira com a qual os objetos do documento HTML são expostos ao seu script.</p> -<h4 id="Relationship_between_JavaScript_Versions_and_ECMAScript_Editions" name="Relationship_between_JavaScript_Versions_and_ECMAScript_Editions">Relação entre as versões do JavaScript e as edições do ECMAScript</h4> -<p>O Netscape trabalhou próximo a Ecma International para produzir a Especificação ECMAScript (ECMA-262). A tabela seguinte descreve a relação entre as versões do JavaScript e as edições do ECMAScript.</p> -<table class="standard-table"> <caption>Tabela 1.2 Versões do JavaScript e edições do ECMAScript</caption> <thead> <tr> <th scope="row">Versão do JavaScript</th> <th scope="col">Relação com a edição do ECMAScript</th> </tr> </thead> <tbody> <tr> <td>JavaScript 1.1</td> <td>O ECMA-262, Edição 1 é baseado no JavaScript 1.1.</td> </tr> <tr> <td>JavaScript 1.2</td> <td>O ECMA-262 não estava completo quando o JavaScript 1.2 foi lançado. O JavaScript 1.2 não é totalmente compatível com o ECMA-262, Edição 1, pelas seguintes razões: <ul> <li>O Netscape desenvolveu características adicionais no JavaScript 1.2 que não foram consideradas no ECMA-262.</li> <li>O ECMA-262 adiciona duas novas características: internacionalização usando Unicode e comportamento uniforme em todas as plataformas. Muitas características do JavaScript 1.2, tais com o objeto <code>Date</code>, eram dependentes de plataforma e usavam um comportamento específico da plataforma.</li> </ul> </td> </tr> <tr> <td> <p>JavaScript 1.3</p> </td> <td> <p>O JavaScript 1.3 é totalmente compatível com o ECMA-262, Edição 1.</p> <p>O JavaScript 1.3 corrigiu as inconsistências que o JavaScript 1.2 tinha com o ECMA-262, mantendo todas as características adicionais do JavaScript 1.2 com a exceção de == e !=, os quais foram mudados conforme o ECMA-262.</p> </td> </tr> <tr> <td> <p>JavaScript 1.4</p> </td> <td> <p>O JavaScript 1.4 é totalmente comatível com o ECMA-262, Edição 1.</p> <p>A terceira versão da especificação ECMAScript não estava finalizada quando o JavaScript 1.4 foi lançado.</p> </td> </tr> <tr> <td>JavaScript 1.5</td> <td>O JavaScript 1.5 é totalmente compatível com o ECMA-262, Edição 3.</td> </tr> </tbody> -</table> -<div class="note"><strong>Nota</strong>: O ECMA-262, Edição 2 consistiu de mudanças editoriais pequenas e correções de bugs da especificação da Edição 1. O grupo de trabalho TC39 da Ecma International está atualmente trabalhando no ECMAScript Edição 4, o qual corresponderá a um lançamento futuro do JavaScript, o JavaScript 2.0.</div> -<p>A <a href="/en/JavaScript/Reference" title="en/JavaScript/Reference">Referência de JavaScript</a> (en) indica quais características da linguagem estão em conformidade com o ECMAScript.</p> -<p>O JavaScript sempre permite incluir características que não fazem parte da Especificação do ECMAScript; O JavaScript é compatível com o ECMASCript; mesmo provendo características adicionais.</p><h4 id="JavaScript_Documentation_versus_the_ECMAScript_Specification" name="JavaScript_Documentation_versus_the_ECMAScript_Specification">Documentação do JavaScript versus a especificação do ECMAScript</h4> -<p>A especificação do ECMAScript é um conjunto de requisitos para a implementação do ECMAScript; ela é útil caso deseje-se determinar, se uma característica do JavaScript é suportada em outras implementações do ECMAScript. Caso planeje-se escrever código JavaScript usando somente características suportadas pelo ECMAScript, então é interessante checar a especificação ECMAScript.</p> -<p>O documento ECMAScript não pretende ajudar programadores de scripts; para informações sobre escrita de scripts, deve-se usar a documentação do JavaScript.</p><h4 id="JavaScript_and_ECMAScript_Terminology" name="JavaScript_and_ECMAScript_Terminology">Terminologia do JavaScript e do ECMAScript</h4> -<p>A especificação do ECMAScript utiliza a terminologia e sintaxe que pode ser desconhecida para um programador JavaScript. Embora a descrição da linguagem possa diferir, a linguagem em si, é a mesma. O JavaScript suporta todas as funcionalidades descritas na especificação ECMAScript.</p> -<p>A documentação do JavaScript descreve aspectos da linguagem que são apropriados para um programador JavaScript. Por exemplo:</p> -<ul> <li>O Objeto Global não é discutido na documentação do JavaScript porque ele não é usado diretamente. Os métodos e propriedades do Objeto Global, os quais são usados, são discutidos na documentação do JavaScript, mas são chamados de funções e propriedades de nível superior.</li> <li>O construtor sem parâmetros (zero argumentos) com os objetos <code>Number</code> e <code>String</code> não é discutido na documentação do JavaScript, pois o gerado é pouco usado. Um construtor de <code>Number</code> sem nenhum argumento, retorna +0, e um construtor de <code>String</code> sem argumentos, retorna "" (uma string vazia).</li> -</ul> -<pre class="script" style="font-size: 16px;">autoPreviousNext("JSGChapters"); -wiki.languages({ - "en": "en/JavaScript/Guide/JavaScript_Overview", - "es": "es/Gu\u00eda_JavaScript_1.5/Concepto_de_JavaScript", - "fr": "fr/Guide_JavaScript_1.5/Aper\u00e7u_de_JavaScript", - "ja": "ja/Core_JavaScript_1.5_Guide/JavaScript_Overview", - "ko": "ko/Core_JavaScript_1.5_Guide/JavaScript_Overview", - "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/Przegl\u0105d_JavaScriptu", - "zh-cn": "cn/Core_JavaScript_1.5_Guide/JavaScript\u603b\u89c8", - "zh-tw": "zh_tw/Core_JavaScript_1.5_教學/JavaScript_概要" -});</pre> diff --git a/files/pt-pt/web/javascript/guia/sobre/index.html b/files/pt-pt/web/javascript/guia/sobre/index.html deleted file mode 100644 index 6957645a40..0000000000 --- a/files/pt-pt/web/javascript/guia/sobre/index.html +++ /dev/null @@ -1,166 +0,0 @@ ---- -title: Sobre este guia -slug: Web/JavaScript/Guia/Sobre ---- -<p>JavaScript é uma linguagem de scripts multiplataforma, baseada em objetos. Este guia explica tudo que é necessário saber sobre como utilizar o JavaScript.</p> - -<h2 id="Novas_caraterísticas_em_versões_do_JavaScript">Novas caraterísticas em versões do JavaScript</h2> - -<pre class="script" style="font-size: 16px;">/* Nota: Para adicionar um link na descrição de uma nova versão do JavaScript, -adicione o número da variável versionList abaixo. A página ligada deve -residir em /en/JavaScript/New_in_JavaScript/N, onde N é o número da versão. */ - -var versionList = ["1.5", "1.6", "1.7", "1.8", "1.8.1", "1.8.5"]; -var s = ""; -<ul> - foreach (var i in versionList){ - let s = "/en/JavaScript/New_in_JavaScript/" .. i; - <li>web.link(s, wiki.getPage(s).title)</li>; - } -</ul>;</pre> - -<h2 id="O_que_já_é_necessário_saber">O que já é necessário saber</h2> - -<p>Este guia assume que já possui os seguintes conhecimentos como base:</p> - -<ul> - <li>Um entendimento geral da Internet e da World Wide Web (WWW).</li> - <li>Bom conhecimento de trabalho com HyperText Markup Language (<a href="/en/HTML" title="en/HTML">HTML</a>).</li> -</ul> - -<p>Alguma experiência de programação com uma linguagem como C ou Visual Basic é útil, mas não necessária.</p> - -<h2 id="Versões_do_JavaScript">Versões do JavaScript</h2> - -<table class="standard-table"> - <caption>Tabela 1 Versões do JavaScript e do Navigator</caption> - <thead> - <tr> - <th scope="col">versão JavaScript</th> - <th scope="col">versão Navigator</th> - </tr> - </thead> - <tbody> - <tr> - <td>JavaScript 1.0</td> - <td>Navigator 2.0</td> - </tr> - <tr> - <td>JavaScript 1.1</td> - <td>Navigator 3.0</td> - </tr> - <tr> - <td>JavaScript 1.2</td> - <td>Navigator 4.0-4.05</td> - </tr> - <tr> - <td>JavaScript 1.3</td> - <td>Navigator 4.06-4.7x</td> - </tr> - <tr> - <td>JavaScript 1.4</td> - <td> </td> - </tr> - <tr> - <td>JavaScript 1.5</td> - <td>Navigator 6.0<br> - Mozilla (navegador open source)</td> - </tr> - <tr> - <td>JavaScript 1.6</td> - <td><a href="/en/Firefox_1.5_for_developers" title="en/Firefox_1.5_for_developers">Firefox 1.5</a>, outros produtos baseados no Mozilla 1.8</td> - </tr> - <tr> - <td>JavaScript 1.7</td> - <td><a href="/en/Firefox_2_for_developers" title="en/Firefox_2_for_developers">Firefox 2</a>, outros produtos baseados no Mozilla 1.8.1</td> - </tr> - <tr> - <td>JavaScript 1.8</td> - <td><a href="/en/Firefox_3_for_developers" title="en/Firefox_3_for_developers">Firefox 3</a>, outros produtos baseados no Gecko 1.9</td> - </tr> - </tbody> -</table> - -<p>Cada versão do Netscape Enterprise Server também suporta diferentes versões do JavaScript. Para ajudar na escrita de scripts compatíveis com múltiplas versões do Enterprise Server, este manual usa uma abreviação para indicar a versão do servidor na qual cada característica foi implementada.</p> - -<table class="standard-table"> - <caption>Tabela 2 Abreviações das versões do Netscape Enterprise Server</caption> - <thead> - <tr> - <th scope="col">Abreviação</th> - <th scope="col">versão Enterprise Server</th> - </tr> - </thead> - <tbody> - <tr> - <td>NES 2.0</td> - <td>Netscape Enterprise Server 2.0</td> - </tr> - <tr> - <td>NES 3.0</td> - <td>Netscape Enterprise Server 3.0</td> - </tr> - </tbody> -</table> - -<h2 id="Onde_encontrar_informações_sobre_JavaScript">Onde encontrar informações sobre JavaScript</h2> - -<p>A documentação do JavaScript inclui os seguintes livros:</p> - -<ul> - <li><a href="/en/JavaScript/Guide" title="en/Core_JavaScript_1.5_Guide">Guia de JavaScript</a> (este guia) fornece informações sobre a linguagem JavaScript e seus objetos.</li> - <li><a href="/en/JavaScript/Reference" title="en/JavaScript/Reference">Referência JavaScript</a> fornece material de referência para a linguagem JavaScript.</li> -</ul> - -<p>Se você é novo no JavaScript, comece com o <a href="/en/JavaScript/Guide" title="en/Core_JavaScript_1.5_Guide">Guia de JavaScript</a>. Uma vez que você tenha uma boa compreensão dos fundamentos, você pode usar a <a href="/en/JavaScript/Reference" title="en/JavaScript/Reference">Referência JavaScript</a> para obter mais detalhes sobre objetos e declarações.</p> - -<h2 id="Dicas_para_aprender_JavaScript">Dicas para aprender JavaScript</h2> - -<p>Começar com o JavaScript é fácil: é necessário apenas um navegador web moderno. Este guia inclui algumas características do JavaScript que estão atualmente disponíveis nas últimas versões do Firefox (e outros navegadores baseados no Gecko), é recomendado, portanto, o uso da versão mais recente do Firefox.</p> - -<h3 id="Um_interpretador_interativo">Um interpretador interativo</h3> - -<p>Uma linha de comando interativa com JavaScript é inestimável para o aprendizado da linguagem, pois permite experimentar código de forma interativa sem ter que salvar um arquivo e recarregar a página. O Console de erros do Firefox, acessível através do menu de Ferramentas, fornece uma maneira simples de testar JavaScript interativamente: Basta entrar uma linha de código e clicar no botão "Executar".</p> - -<p><img alt="Image:ErrorConsole.png" class="internal" src="/@api/deki/files/192/=ErrorConsole.png"></p> - -<h3 id="Firebug">Firebug</h3> - -<p>Uma linha de comando interativa mais avançada está disponível com o uso do<a class="external" href="http://www.getfirebug.com/"> Firebug</a>, uma extensão de terceiros para o Firefox. O Firebug também fornece um inspetor DOM avançado, um depurador de JavaScript, uma ferramenta de análise e vários outros utilitários.</p> - -<p><img alt="Image:Firebug.png" class="internal" src="/@api/deki/files/204/=Firebug.png"></p> - -<p>Um dos mais úteis benefícios proporcionados pelo Firebug é <code>console.log()</code>, uma função que imprime seus argumentos no console do Firebug. Diferentemente de outras linguagens de programação, o JavaScript não possui um conceito de impressão para a saída padrão. O <code>console.log()</code> fornece uma alternativa útil, tornando mais fácil ver o que seu programa está fazendo.</p> - -<p>Muitos dos exemplos neste guia usam <code>alert()</code> para exibir mensagens conforme são executados. Tendo o Firebug instalado, pode ser usando <code>console.log()</code> ao invés de <code>alert()</code> ao rodar estes exemplos.</p> - -<h2 id="Convenções_de_documento">Convenções de documento</h2> - -<p>Aplicações JavaScript rodam em muitos sistemas operacionais; a informação neste livro aplica-se a todas as versões. Os caminhos de arquivos e diretórios são dados no formato Windows (com contrabarras separando os nomes dos diretórios). Para versões Unix, os caminhos são os mesmo, exceto por serem usadas barras ao invés de contrabarras para separar os diretórios.</p> - -<p>Este guia usa localizador padrão de recursos (<em>uniform resource locators</em> (URL)) da seguinte forma:</p> - -<p><code>http://<em>server</em>.<em>domain</em>/<em>path</em>/<em>file</em>.html</code></p> - -<p>Nestas URL, <em>server</em> representa o nome do servidor no qual a aplicação é rodada, tal como <code>research1</code> ou <code>www</code>; <em>domain</em> representa seu domínio de internet, como <code>netscape.com</code> ou <code>uiuc.edu</code>; <em>path</em> representa a estrutura do diretório no servidor; e <em>file</em><code>.html</code> representa o nome de um arquivo individual. No geral, itens em itálico em são <em>placeholders</em> e itens em fonte monoespaçada normal são literais. Se o servidor possuir <em>Secure Sockets Layer</em> (SSL) habilitado, pode ser usado <code>https</code> ao invés de <code>http</code> na URL.</p> - -<p>Este guia utiliza as seguintes convenções de fontes:</p> - -<ul> - <li><code>A fonte mono espaçada</code> é utilziada para amostras de código e listagens de código, API e elementos da linguagem (como nomes de métodos e propriedades), nome de arquivos, caminhos, diretórios, tags HTML, e qualquer texto que possa ser digitado na tela. (<code><em>A fonte monoespaçada itálica</em></code> é usada para <em>placeholders </em>embutidos no código.)</li> - <li><em>O tipo itálico</em> é usado para títulos de livros, ênfase, variáveis e <em>placeholders</em>, e palavras usadas em sentido literal.</li> - <li><strong>O tipo negrito</strong> é usado para termos de glossário.</li> -</ul> - -<pre class="script" style="font-size: 16px;">autoPreviousNext("JSGChapters"); -wiki.languages({ - "en": "en/JavaScript/Guide/About", - "es": "es/Gu\u00eda_JavaScript_1.5/Acerca_de_esta_gu\u00eda", - "fr": "fr/Guide_JavaScript_1.5/\u00c0_propos", - "ja": "ja/Core_JavaScript_1.5_Guide/About", - "ko": "ko/Core_JavaScript_1.5_Guide/About", - "pl": "pl/Przewodnik_po_j\u0119zyku_JavaScript_1.5/O_tym_przewodniku", - "zh-cn": "cn/Core_JavaScript_1.5_Guide/\u5173\u4e8e", - "zh-tw": "zh_tw/Core_JavaScript_1.5_教學/關於" -}) -</pre> diff --git a/files/pt-pt/web/javascript/guia/valores,_variáveis_e_literais/index.html b/files/pt-pt/web/javascript/guia/valores,_variáveis_e_literais/index.html deleted file mode 100644 index c2cbc7f3db..0000000000 --- a/files/pt-pt/web/javascript/guia/valores,_variáveis_e_literais/index.html +++ /dev/null @@ -1,547 +0,0 @@ ---- -title: 'Valores, Variáveis e Literais' -slug: 'Web/JavaScript/Guia/Valores,_Variáveis_e_Literais' ---- -<p>Este capítulo discute valores reconhecidos pelo JavaScript e descreve a construção de blocos fundamentais de expressões em JavaScript: variáveis, constantes e literais.</p> - -<h2 id="Valores">Valores</h2> - -<p>O JavaScript reconhece os seguintes tipos de valores:</p> - -<ul> - <li><a href="/en/JavaScript/Reference/Global_Objects/Number" title="en/JavaScript/Reference/Global Objects/Number">Números</a> (en), como 42 ou 3,14159</li> - <li>Valores <a href="/en/JavaScript/Reference/Global_Objects/Boolean" title="en/JavaScript/Reference/Global Objects/Boolean">lógicos (Booleanos)</a> (en), <code>true</code> ou <code>false</code></li> - <li><a href="/en/JavaScript/Reference/Global_Objects/String" title="en/JavaScript/Reference/Global Objects/String">Strings</a> (en), tais como "Howdy!"</li> - <li><code>null</code>, um palavra chave especial denotando um valor nulo; <code>null</code> também é um valor primitivo. Como JavaScript é sensível a maiúsculas, <code>null</code> não é a mesma coisa que <code>Null</code>, <code>NULL</code>, ou qualquer outra variante</li> - <li><code><a href="/en/JavaScript/Reference/Global_Objects/undefined" title="en/JavaScript/Reference/Global Objects/undefined">undefined</a></code> (en), uma propriedade de alto nível a qual possui o valor indefinido; <code>undefined</code> também é um valor primitivo.</li> -</ul> - -<p>Este conjunto de tipos de valores relativamente pequeno, permite realizar funções úteis com suas aplicações. Não há distinção explícita entre números inteiros e reais. Nem existe um tipo de dados de datas explícito em JavaScript. Entretanto, é possível utilizar o objeto <code><a href="/en/JavaScript/Reference/Global_Objects/Date" title="en/JavaScript/Reference/Global Objects/Date">Date</a></code> (en) e seus métodos para lidar com datas.</p> - -<p><a href="/en/JavaScript/Reference/Global_Objects/Object" title="en/JavaScript/Reference/Global Objects/Object">Objetos</a> (en) e <a href="/en/JavaScript/Reference/Global_Objects/Function" title="en/JavaScript/Reference/Global Objects/Function">funções</a> (en) são os outros elementos fundamentias da linguagem. Pode-se pensar em objetos como nomes nos quais podem ser guardados valores, e funções como procedimentos que sua aplicação pode executar.</p> - -<h3 id="Conversão_de_tipos_de_dados">Conversão de tipos de dados</h3> - -<p>O JavaScript é uma linguagem de tipagem dinâmica. Isto significa que não é necessário especificar o tipo de dado de uma variável quando ela for declarada, e tipos de dados são automaticamento convertidos conforme necessário durante a execução do script. Então, por exemplo, pode-se definir uma variável como:</p> - -<pre>var resposta = 42; -</pre> - -<p>E depois, pode-se atribuir para a mesma variável um valor de string, por exemplo:</p> - -<pre class="deki-transform">resposta = "Obrigado pelos peixes..."; -</pre> - -<p>Como o JavaScript possui tipagem dinâmica, esta atribuição não gera uma mensagem de erro.</p> - -<p>Em expressões envolvendo valores numéricos e strings com o operador +, o JavaScript converte valores numérios para string. Por exemplo, considere as seguintes declarações:</p> - -<pre class="eval deki-transform">x = "A resposta é " + 42 // retorna "A resposta é 42" -y = 42 + " é a resposta" // retorna "42 é a resposta" -</pre> - -<p>Em declarações envolvendo outros operadores, o JavaScript não converte valores numérico para strings. Por exemplo:</p> - -<pre class="eval deki-transform">"37" - 7 // retorna 30 -"37" + 7 // retorna "377"</pre> - -<h2 id="Variáveis">Variáveis</h2> - -<p>Variáveis são usadas como nomes simbólicos para valores em sua aplicação. Os nomes das variáveis, chamadas <em>identificadores</em>, de acordo com certas regras.</p> - -<p>Um identificador JavaScript deve começar com uma letra, sublinhado (_), ou cifrão ($); caracteres subsequentes podem também ser dígitos (0-9). Como o JavaScript é sensível a maiúsculas, as letras incluem os caracteres de "A" até "Z" (maiúsculas) e os caracteres de "a" até "z" (minúsculas).</p> - -<p>A partir do JavaScript 1.5 é possível usar letras em ISO 8859-1 ou Unicode tais como å e ü nos identificadores. Também é possível usar as <a href="#Sequências de escape em Unicode">Sequências de escape em Unicode</a> \uXXXX como caracteres nos identificadores.</p> - -<p>Alguns exemplos de nomes possíveis são: <code>Number_hits</code>, <code>temp99</code> e <code>_name</code>.</p> - -<h3 id="Declaração_de_variáveis">Declaração de variáveis</h3> - -<p>Você pode declarar uma variável de duas maneiras:</p> - -<ul> - <li>Com a palavra chave <a href="/en/JavaScript/Reference/Statements/var" title="en/JavaScript/Reference/Statements/var">var</a>. Por exemplo, <code>var x = 42</code>. Esta sintaxe pode ser usada para declarar tanto variáveis <a href="#Variable_Scope">locais quanto globais</a> (en).</li> - <li>Simplesmente atribuindo um valor a ela. Por exemplo, <code>x = 42</code>. Isto sempre declara uma <a href="#Global_Variables">variável global</a> (en) e gera um aviso estrito do JavaScript. Esta variante não deve ser usada.</li> -</ul> - -<h3 id="Avaliação_de_variáveis">Avaliação de variáveis</h3> - -<p>Uma variável declarada usando-se a declaração <code>var</code> sem possuir um valor inicial especificado possui o valor <code><a href="/en/JavaScript/Reference/Global_Objects/undefined" title="en/JavaScript/Reference/Global Objects/undefined">undefined</a></code>.</p> - -<p>Uma tentativa de acesso a uma variável não declarada resultará no lançamento de uma exceção <code>ReferenceError</code>:</p> - -<pre class="eval deki-transform">var a; -print("O valor de a é " + a); // imprime "O valor de a é undefined" -print("O valor de b é " + b); // lança a exceção ReferenceError -</pre> - -<p>Você pode usar <code>undefined</code> para determinar quando uma variável possui um valor. No código a seguir, a variável <code>input</code> não possui um valor atribuido e a declaração <code><a href="/en/JavaScript/Reference/Statements/if...else" title="en/Core_JavaScript_1.5_Reference/Statements/if...else">if</a></code> é avaliada como <code>true</code>.</p> - -<pre class="eval deki-transform">var input; -if(input === undefined){ - doThis(); -} else { - doThat(); -} -</pre> - -<p><span class="comment">O valor</span> <code>undefined</code> comporta-se como <code>false</code> quando usado em um contexto booleano. Por exemplo, o código a seguir executa a função <code>myFunction</code> porque o elemento <code>myArray</code> não está definido:</p> - -<pre class="eval deki-transform">var myArray = new Array(); -if (!myArray[0]) myFunction(); -</pre> - -<p>Quando você avalia uma variável nula, o valor nulo comporta-se como um 0 no contexto numérico e como falso em contextos booleanos. Por exemplo</p> - -<pre class="eval deki-transform">var n = null; -print(n * 32); // imprime 0 -</pre> - -<h3 id="Escopo_de_variáveis">Escopo de variáveis</h3> - -<p>Quando uma variável é declarada de fora de qualquer função, ele é chamada de variável <em>global</em>, pois ela está disponível para qualquer outro código no documento atual. Quando você declara uma variável dentro de uma função, ela é chamada de variável <em>local</em>, pois ela está disponível somente dentro dessa função.</p> - -<p>O JavaScript não possui um escopo de <a href="/en/JavaScript/Guide/Statements#Block_Statement" title="en/JavaScript/Guide/Statements#Block Statement">declaração de blocos</a> (en); ao contrário, será local para o código interno ao bloco. Por exemplo, o código a seguir imprimirá <code>0</code> ao invés de lançar a exceção <span><span class="comment">ReferenceError se</span></span> <code>condition</code> é <code>false</code>:</p> - -<pre class="eval deki-transform">if (condition) { - var x = 5; -} -print(x ? x : 0); -</pre> - -<p>Outra coisa não usual sobre variáveis em JavaScript é que é possível referir-se a uma variável declarada depois, sem receber uma exceção. Este conceito é conhecido como <em>hoisting</em>; as variáveis no JavaScript são levadas para o topo da função ou da declaração. Entretanto, as variáveis não inicializadas retornarão um valor <code>undefined</code>.</p> - -<pre class="eval deki-transform">print(x === undefined); // prints "true" -var x = 3; - -//will return a value of undefined -var myvar = "my value"; - -(function() { - alert(myvar);//undefined - var myvar = "local value" -})(); -</pre> - -<h3 id="Variáveis_globais">Variáveis globais</h3> - -<p><span class="comment">necessário links para as páginas discutindo cadeias no âmbito do objeto global</span> Variáveis globais são, na verdade, propriedade de um <em>objeto global</em>. Em páginas web o objeto global é <code><a href="/en/DOM/window" title="en/DOM/window">window</a></code>, então você pode configurar e acessar variáveis globais usando a sintaxe<code> window.<em>variable</em></code>.</p> - -<p>Consequentemente, você pode acessar variáveis globais declaradas em uma janela ou quadro de alguma outra janela ou quadro, especificando o nome do mesmo. Por exemplo, se uma variável chamada <code>phoneNumber</code> é declarada em um documento <code>FRAMESET</code>, você pode referir-se a esta variável a partir de um frame herdeiro como <code>parent.phoneNumber</code>.</p> - -<h3 id="Veja_também">Veja também</h3> - -<p><a href="/en/Sharp_variables_in_JavaScript" title="en/Sharp_variables_in_JavaScript">Sharp variables in JavaScript</a> (en)</p> - -<h2 id="Constantes">Constantes</h2> - -<p>Você pode criar elementos "somente leitura", nomeados constantes com a palavra chave <code><a href="/en/JavaScript/Reference/Statements/const" title="en/Core_JavaScript_1.5_Reference/Statements/const">const</a></code>. A sintaxe de um identificador constante é a mesma para um identificador de variáveis: deve começar com uma letra ou sublinhado e pode conter caracteres alfabéticos, numéricos ou sublinhado.</p> - -<pre class="eval deki-transform">const prefix = '212'; -</pre> - -<p>Uma constante não pode ter seu valor mudado através de uma atribuição ou ser declarada novamente enquanto o script estiver rodando.</p> - -<p>As regras de escopo para constantes são as mesmas que as das variáveis, exceto que a palavra chave <code>const</code> é sempre necessária, mesmo para constantes globais. Se uma palavra chave é omitida, o identificador é assumido como uma variável.</p> - -<p>Você não pode declarar uma constante com o mesmo nome de uma função ou variável no mesmo escopo. Por exemplo:</p> - -<pre class="eval deki-transform">// ISTO CAUSARA UM ERRO -function f() {}; -const f = 5; - -// ISTO TAMBEM CAUSARA UM ERRO -function f() { - const g = 5; - var g; - - // declaracoes -} -</pre> - -<h2 id="Literais">Literais</h2> - -<p>Você usa literais para representar valores em JavaScript. Estes valores são fixos, não variáveis, que você fornece <em>literalmente</em> no seu script. Esta seção descreve os seguintes tipos de literais:</p> - -<ul> - <li><a href="#Ordenação de literais">Ordenação de literais</a></li> - <li><a href="#Booleanos literais">Booleanos literais</a></li> - <li><a href="#Pontos flutuantes literais">Pontos flutuantes literais</a></li> - <li><a href="#Inteiros">Inteiros</a></li> - <li><a href="#Objetos literais">Objetos literais</a></li> - <li><a href="#Strings literais">Strings literais</a></li> -</ul> - -<h3 id="Ordenação_de_literais"><a id="Ordenação de literais" name="Ordenação de literais">Ordenação de literais</a></h3> - -<p>Um literal ordenado é uma lista de zero ou mais expressões, cada qual representando um elemento ordenado, armazenado em colchetes ([]). Quando você cria uma ordenação usando um literal ordenado, ele é inicializado com os valores especificados como seus elementos e seu comprimento configurado para o número de argumentos especificados.</p> - -<p>O exemplo a seguir cria uma ordenação <code>coffees</code> com três elementos e o comprimento de três:</p> - -<pre class="eval deki-transform">var coffees = ["French Roast", "Colombian", "Kona"]; -</pre> - -<p><strong>Nota</strong> Uma ordenação literal é um tipo de inicializador de objeto. Veja<a href="/en/JavaScript/Guide/Working_with_Objects#Using_Object_Initializers" title="en/JavaScript/Guide/Working with Objects#Using Object Initializers"> Using Object Initializers</a> (en).</p> - -<p>Se uma ordenação é criada usando um literal em um alto nível de script, o JavaScript interpreta a ordenação cada vez que uma expressão contendo a ordenação literal é avaliada. Adicionalmente, um literal usado em uma função é criado cada vez que a função é chamada.</p> - -<p>Ordenações literais são também objetos <code>Array</code>. Veja <a href="/en/JavaScript/Guide/Predefined_Core_Objects#Array_Object" title="en/JavaScript/Guide/Predefined Core Objects#Array Object">Array Object</a> (en) para detalhes sobre objetos <code>Array</code>.</p> - -<h4 id="Vírgulas_extras_em_literais_ordenados">Vírgulas extras em literais ordenados</h4> - -<p>Não é necessário especificar todos os elementos de um literal ordenado. Se forem colocadas duas vírgulas em uma coluna, a ordenação é criada com espaços para elementos não especificados. O exemplo seguinte mostra a ordenação <code>fish</code>:</p> - -<pre class="eval deki-transform">var fish = ["Lion", , "Angel"]; -</pre> - -<p>Esta ordenação possui dois elementos com valores e um elemento vazio (<code>fish[0]</code> é "Lion", <code>fish[1]</code> é <code>undefined</code> e <code>fish[2]</code> é "Angel").</p> - -<p>Caso seja inserida uma última vírgula ao fim da lista de elementos, a vírgula é ignorada. No exemplo a seguir, o comprimento da ordenação é três. Não há <code>myList[3]</code>. Todas as outras vírgulas da lista indicam um novo elemento.</p> - -<pre class="eval deki-transform">var myList = ['home', , 'school', ]; -</pre> - -<p>No exemplo a seguir, o comprimento da ordenação é quatro, e <code>myList[0]</code> e <code>myList[2]</code> estão faltando.</p> - -<pre class="eval deki-transform">var myList = [ , 'home', , 'school']; -</pre> - -<p>No exemplo seguinte, o comprimento da ordenação é quatro, e <code>myList[1]</code> e <code>myList[3]</code> estão faltando. Somente a última vírgula é ignorada.</p> - -<pre class="eval deki-transform">var myList = ['home', , 'school', , ]; -</pre> - -<h3 id="Booleanos_literais"><a id="Booleanos literais" name="Booleanos literais">Booleanos literais</a></h3> - -<p>O tipo Booleano possui dois valores literais: <code>true</code> e <code>false</code>.</p> - -<p>Não confunda-os com os valores Booleanos primitivos <code>true</code> e <code>false</code> com os valores verdadeiro e falso do objeto Booleano. O objeto Booleano é um invólucro ao redor do tipo de dado Booleano. Veja <a href="/en/JavaScript/Guide/Predefined_Core_Objects#Boolean_Object" title="en/JavaScript/Guide/Predefined Core Objects#Boolean Object">Boolean Object</a> (en) para mais informações.</p> - -<h3 id="Inteiros_2"><a id="Inteiros" name="Inteiros">Inteiros</a></h3> - -<p>Inteiros podem ser expressos na base decimal (base 10), hexadecimal (base 16) e octal (base 8). Um inteiro decimal literal consiste em uma sequência de dígitos sem um 0 (zero) no início. Um 0 (zero) no início de um inteiro literal indica que se trata de um octal; um 0x (ou 0X) indica hexadecimal. Inteiros hexadecimais podem incluir dígitos (0-9) e as letras de a-f e A-F. Inteiros octais podem incluir somente dígitos 0-7.</p> - -<p>Inteiros octais literais são obsoletos e foram removidos do padrão ECMA-262, Edição 3. O JavaScript 1.5 ainda os suporta para compatibilidade com versões anteriores.</p> - -<p>Alguns exemplo de inteiros literais são:</p> - -<pre class="eval">0, 117 e -345 (decimal, base 10) -015, 0001 e -077 (octal, base 8) -0x1123, 0x00111 e -0xF1A7 (hexadecimal, "hex" ou base 16) -</pre> - -<h3 id="Pontos_flutuantes_literais"><a id="Pontos flutuantes literais" name="Pontos flutuantes literais">Pontos flutuantes literais</a></h3> - -<p>Um literal de ponto flutuante pode possuir as seguintes partes:</p> - -<ul> - <li>Um inteiro decimal, o qual pode ser assinado (precedido por "+" ou "-"),</li> - <li>Um ponto decimal ("."),</li> - <li>Uma fração (outro número decimal),</li> - <li>Um expoente.</li> -</ul> - -<p>A parte do expoente é um "e" ou "E" seguido por um inteiro, o qual pode ser assinado (precedido por "+" ou "-"). Um literal de ponto flutuante deve ter ao menos um dígito e um ponto decimal ou "e" (ou "E").</p> - -<p>Alguns exemplos de pontos flutuantes literais são 3.1415, -3.1E12, .1e12, and 2E-12.</p> - -<p>Mais claramente, a sintaxe é:</p> - -<pre class="eval">[digitos][.digitos][(E|e)[(+|-)]digitos] -</pre> - -<p>Por exemplo:</p> - -<pre class="eval">3.14 -2345.789 -.3333333333333333333 -</pre> - -<h3 id="Objetos_literais"><a id="Objetos literais" name="Objetos literais">Objetos literais</a></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 ({}). 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>; the second element, the <code>getCar</code> property, invokes a function <code>(CarTypes("Honda"));</code> the third element, the <code>special</code> property, uses an existing variable (<code>Sales</code>).</p> - -<pre class="eval deki-transform">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 }; - -document.write(car.myCar); // Saturn -document.write(car.getCar); // Honda -document.write(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="eval deki-transform">var car = { manyCars: {a: "Saab", "b": "Jeep"}, 7: "Mazda" }; - -document.write(car.manyCars.b); // Jeep -document.write(car[7]); // Mazda -</pre> - -<p>Please note:</p> - -<pre class="eval deki-transform">var foo = {a: "alpha", 2: "two"}; -document.write(foo.a); // alpha -document.write(foo[2]); // two -//document.write(foo.2); // Error: missing ) after argument list -//document.write(foo[a]); // Error: a is not defined -document.write(foo["a"]); // alpha -document.write(foo["2"]); // two -</pre> - -<h3 id="Strings_literais"><a id="Strings literais" name="Strings literais">Strings literais</a></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> - -<ul> - <li><code>"foo"</code></li> - <li><code>'bar'</code></li> - <li><code>"1234"</code></li> - <li><code>"one line \n another line"</code></li> - <li><code>"John's cat"</code></li> -</ul> - -<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="deki-transform">"John's cat".length -</pre> - -<p>You should use string literals unless you specifically need to use a String object. See <a href="/en/JavaScript/Guide/Predefined_Core_Objects#String_Object" title="en/JavaScript/Guide/Predefined Core Objects#String Object">String Object</a> for details on <code>String</code> objects.</p> - -<h4 id="Usando_caracteres_especiais_em_strings">Usando caracteres especiais em 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="eval deki-transform">"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 2.1 JavaScript special characters</caption> - <thead> - <tr> - <th scope="col">Character</th> - <th scope="col">Meaning</th> - </tr> - </thead> - <tbody> - <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> - <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> - <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="#Sequências de escape em Unicode">Unicode Escape Sequences</a>.</td> - </tr> - </tbody> -</table> - -<h4 id="Caracteres_de_escape">Caracteres de escape</h4> - -<p>For characters not listed in Table 2.1, 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="eval deki-transform">var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service."; -document.write(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="eval deki-transform">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>var str = "this string \ -is broken \ -across multiple\ -lines."</pre> - -<p>Although JavaScript does not have "heredoc" syntax, you can get close by adding a linebreak escape and an escaped linebreak at the end of each line:</p> - -<pre>var poem = -"Roses are red,\n\ -Violets are blue.\n\ -I'm schizophrenic,\n\ -And so am I." -</pre> - -<h2 id="Unicode">Unicode</h2> - -<p>Unicode is a universal character-coding standard for the interchange and display of principal written languages. It covers the languages of the Americas, Europe, Middle East, Africa, India, Asia, and Pacifica, as well as historic scripts and technical symbols. Unicode allows for the exchange, processing, and display of multilingual texts, as well as the use of common technical and mathematical symbols. It hopes to resolve internationalization problems of multilingual computing, such as different national character standards. Not all modern or archaic scripts, however, are currently supported.</p> - -<p>The Unicode character set can be used for all known encoding. Unicode is modeled after the ASCII (American Standard Code for Information Interchange) character set. It uses a numerical value and name for each character. The character encoding specifies the identity of the character and its numeric value (code position), as well as the representation of this value in bits. The 16-bit numeric value (code value) is defined by a hexadecimal number and a prefix U, for example, U+0041 represents A. The unique name for this value is LATIN CAPITAL LETTER A.</p> - -<p><strong>Unicode is not supported in versions of JavaScript prior to 1.3.</strong></p> - -<h3 id="Compatibilidade_do_Unicode_com_ASCII_e_ISO">Compatibilidade do Unicode com ASCII e ISO</h3> - -<p>Unicode is fully compatible with the International Standard ISO/IEC 10646-1; 1993, which is a subset of ISO 10646.</p> - -<p>Several encoding standards (including UTF-8, UTF-16 and ISO UCS-2) are used to physically represent Unicode as actual bits.</p> - -<p>The UTF-8 encoding of Unicode is compatible with ASCII characters and is supported by many programs. The first 128 Unicode characters correspond to the ASCII characters and have the same byte value. The Unicode characters U+0020 through U+007E are equivalent to the ASCII characters 0x20 through 0x7E. Unlike ASCII, which supports the Latin alphabet and uses a 7-bit character set, UTF-8 uses between one and four octets for each character ("octet" meaning a byte, or 8 bits.) This allows for several million characters. An alternative encoding standard, UTF-16, uses two octets to represent Unicode characters. An escape sequence allows UTF-16 to represent the whole Unicode range by using four octets. The ISO UCS-2 (Universal Character Set) uses two octets.</p> - -<p>JavaScript and Navigator support for UTF-8/Unicode means you can use non-Latin, international, and localized characters, plus special technical symbols in JavaScript programs. Unicode provides a standard way to encode multilingual text. Since the UTF-8 encoding of Unicode is compatible with ASCII, programs can use ASCII characters. You can use non-ASCII Unicode characters in the comments, string literals, identifiers, and regular expressions of JavaScript.</p> - -<h3 id="Sequências_de_escape_em_Unicode"><a id="Sequências de escape em Unicode" name="Sequências de escape em Unicode">Sequências de escape em Unicode</a></h3> - -<p>You can use the Unicode escape sequence in string literals, regular expressions, and identifiers. The escape sequence consists of six ASCII characters: \u and a four-digit hexadecimal number. For example, \u00A9 represents the copyright symbol. Every Unicode escape sequence in JavaScript is interpreted as one character.</p> - -<p>The following code returns the copyright symbol and the string "Netscape Communications".</p> - -<pre class="deki-transform">var x = "\u00A9 Netscape Communications";</pre> - -<p>The following table lists frequently used special characters and their Unicode value.</p> - -<table class="standard-table"> - <caption>Table 2.2 Unicode values for special characters</caption> - <thead> - <tr> - <th scope="col">Category</th> - <th scope="col">Unicode value</th> - <th scope="col">Name</th> - <th scope="col">Format name</th> - </tr> - </thead> - <tbody> - <tr> - <td rowspan="4">White space values<br> - <br> - <br> - </td> - <td>\u0009</td> - <td>Tab</td> - <td><TAB></td> - </tr> - <tr> - <td>\u000B</td> - <td>Vertical Tab</td> - <td><VT></td> - </tr> - <tr> - <td>\u000C</td> - <td>Form Feed</td> - <td><FF></td> - </tr> - <tr> - <td>\u0020</td> - <td>Space</td> - <td><SP></td> - </tr> - <tr> - <td rowspan="2">Line terminator values<br> - </td> - <td>\u000A</td> - <td>Line Feed</td> - <td><LF></td> - </tr> - <tr> - <td>\u000D</td> - <td>Carriage Return</td> - <td><CR></td> - </tr> - <tr> - <td rowspan="5">Additional Unicode escape sequence values<br> - <br> - <br> - <br> - </td> - <td>\u0008</td> - <td>Backspace</td> - <td><BS></td> - </tr> - <tr> - <td>\u0009</td> - <td>Horizontal Tab</td> - <td><HT></td> - </tr> - <tr> - <td>\u0022</td> - <td>Double Quote</td> - <td>"</td> - </tr> - <tr> - <td>\u0027</td> - <td>Single Quote</td> - <td>'</td> - </tr> - <tr> - <td>\u005C</td> - <td>Backslash</td> - <td>\</td> - </tr> - </tbody> -</table> - -<p>The JavaScript use of the Unicode escape sequence is different from Java. In JavaScript, the escape sequence is never interpreted as a special character first. For example, a line terminator escape sequence inside a string does not terminate the string before it is interpreted by the function. JavaScript ignores any escape sequence if it is used in comments. In Java, if an escape sequence is used in a single comment line, it is interpreted as an Unicode character. For a string literal, the Java compiler interprets the escape sequences first. For example, if a line terminator escape character (e.g., \u000A) is used in Java, it terminates the string literal. In Java, this leads to an error, because line terminators are not allowed in string literals. You must use \n for a line feed in a string literal. In JavaScript, the escape sequence works the same way as \n.</p> - -<h3 id="Caracteres_Unicode_em_arquivos_JavaScript">Caracteres Unicode em arquivos JavaScript</h3> - -<p>Earlier versions of <a href="/en/Gecko" title="en/Gecko">Gecko</a> assumed the Latin-1 character encoding for JavaScript files loaded from XUL. Starting with Gecko 1.8, the character encoding is inferred from the XUL file's encoding. Please see <a href="/en/International_characters_in_XUL_JavaScript" title="en/International_characters_in_XUL_JavaScript">International characters in XUL JavaScript</a> for more information.</p> - -<h3 id="Exibindo_caracteres_com_Unicode">Exibindo caracteres com Unicode</h3> - -<p>You can use Unicode to display the characters in different languages or technical symbols. For characters to be displayed properly, a client such as Mozilla Firefox or Netscape needs to support Unicode. Moreover, an appropriate Unicode font must be available to the client, and the client platform must support Unicode. Often, Unicode fonts do not display all the Unicode characters. Some platforms, such as Windows 95, provide partial support for Unicode.</p> - -<p>To receive non-ASCII character input, the client needs to send the input as Unicode. Using a standard enhanced keyboard, the client cannot easily input the additional characters supported by Unicode. Sometimes, the only way to input Unicode characters is by using Unicode escape sequences.</p> - -<p>For more information on Unicode, see the <a class="external" href="http://www.unicode.org/">Unicode Home Page</a> and The Unicode Standard, Version 2.0, published by Addison-Wesley, 1996.</p> - -<pre class="script" style="font-size: 16px;">autoPreviousNext("JSGChapters");</pre> |