From 2c2df5ea01eb5cd8b9ea226b2869337e59c5fe3e Mon Sep 17 00:00:00 2001 From: Florian Merz Date: Thu, 11 Feb 2021 14:50:24 +0100 Subject: unslug pt-pt: move --- .../web/javascript/data_structures/index.html | 297 ++++++++ .../web/javascript/estruturas_de_dados/index.html | 297 -------- .../pt-pt/web/javascript/gestao_memoria/index.html | 187 ----- .../guia/detalhes_do_modelo_de_objeto/index.html | 735 ------------------ .../guia/expressoes_e_operadores/index.html | 832 --------------------- .../guia/gram\303\241tica_e_tipos/index.html" | 641 ---------------- files/pt-pt/web/javascript/guia/index.html | 123 --- .../guia/introdu\303\247\303\243o/index.html" | 137 ---- .../index.html" | 47 -- files/pt-pt/web/javascript/guia/sobre/index.html | 166 ---- .../index.html" | 547 -------------- .../guide/details_of_the_object_model/index.html | 735 ++++++++++++++++++ .../javascript/guide/grammar_and_types/index.html | 641 ++++++++++++++++ files/pt-pt/web/javascript/guide/index.html | 123 +++ .../web/javascript/guide/introduction/index.html | 137 ++++ .../web/javascript/memory_management/index.html | 187 +++++ .../o_que_\303\251_o_javascript/index.html" | 13 - .../web/javascript/reference/about/index.html | 52 ++ .../deprecated_and_obsolete_features/index.html | 289 +++++++ .../index.html" | 113 --- .../errors/unnamed_function_statement/index.html | 113 +++ .../bloco/index.html" | 116 --- .../for/index.html" | 145 ---- .../index.html" | 150 ---- .../return/index.html" | 148 ---- .../throw/index.html" | 271 ------- .../reference/funcionalidades_obsoletas/index.html | 289 ------- .../reference/funcoes/arguments/index.html | 228 ------ .../reference/funcoes/funcoes_seta/index.html | 399 ---------- .../web/javascript/reference/funcoes/index.html | 594 --------------- .../reference/funcoes/parametros_rest/index.html | 234 ------ .../reference/functions/arguments/index.html | 228 ++++++ .../reference/functions/arrow_functions/index.html | 399 ++++++++++ .../web/javascript/reference/functions/index.html | 594 +++++++++++++++ .../reference/functions/rest_parameters/index.html | 234 ++++++ .../asyncfunction/prototype/index.html | 55 -- .../global_objects/number/prototype/index.html | 131 ---- .../global_objects/object/prototype/index.html | 199 ----- .../operadores/fun\303\247\303\243o/index.html" | 139 ---- .../web/javascript/reference/operadores/index.html | 309 -------- .../operadores/operador_virgula/index.html | 94 --- .../operadores/precedencia_operador/index.html | 461 ------------ .../reference/operators/comma_operator/index.html | 94 +++ .../reference/operators/function/index.html | 139 ++++ .../web/javascript/reference/operators/index.html | 309 ++++++++ .../operators/operator_precedence/index.html | 461 ++++++++++++ .../web/javascript/reference/sobre/index.html | 52 -- .../reference/statements/block/index.html | 116 +++ .../javascript/reference/statements/for/index.html | 145 ++++ .../web/javascript/reference/statements/index.html | 150 ++++ .../reference/statements/return/index.html | 148 ++++ .../reference/statements/throw/index.html | 271 +++++++ files/pt-pt/web/javascript/shells/index.html | 29 + 53 files changed, 5891 insertions(+), 7852 deletions(-) create mode 100644 files/pt-pt/web/javascript/data_structures/index.html delete mode 100644 files/pt-pt/web/javascript/estruturas_de_dados/index.html delete mode 100644 files/pt-pt/web/javascript/gestao_memoria/index.html delete mode 100644 files/pt-pt/web/javascript/guia/detalhes_do_modelo_de_objeto/index.html delete mode 100644 files/pt-pt/web/javascript/guia/expressoes_e_operadores/index.html delete mode 100644 "files/pt-pt/web/javascript/guia/gram\303\241tica_e_tipos/index.html" delete mode 100644 files/pt-pt/web/javascript/guia/index.html delete mode 100644 "files/pt-pt/web/javascript/guia/introdu\303\247\303\243o/index.html" delete mode 100644 "files/pt-pt/web/javascript/guia/introdu\303\247\303\243o_ao_javascript/index.html" delete mode 100644 files/pt-pt/web/javascript/guia/sobre/index.html delete mode 100644 "files/pt-pt/web/javascript/guia/valores,_vari\303\241veis_e_literais/index.html" create mode 100644 files/pt-pt/web/javascript/guide/details_of_the_object_model/index.html create mode 100644 files/pt-pt/web/javascript/guide/grammar_and_types/index.html create mode 100644 files/pt-pt/web/javascript/guide/index.html create mode 100644 files/pt-pt/web/javascript/guide/introduction/index.html create mode 100644 files/pt-pt/web/javascript/memory_management/index.html delete mode 100644 "files/pt-pt/web/javascript/o_que_\303\251_o_javascript/index.html" create mode 100644 files/pt-pt/web/javascript/reference/about/index.html create mode 100644 files/pt-pt/web/javascript/reference/deprecated_and_obsolete_features/index.html delete mode 100644 "files/pt-pt/web/javascript/reference/errors/declara\303\247\303\243o_fun\303\247\303\243o_sem_nome/index.html" create mode 100644 files/pt-pt/web/javascript/reference/errors/unnamed_function_statement/index.html delete mode 100644 "files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/bloco/index.html" delete mode 100644 "files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/for/index.html" delete mode 100644 "files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/index.html" delete mode 100644 "files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/return/index.html" delete mode 100644 "files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/throw/index.html" delete mode 100644 files/pt-pt/web/javascript/reference/funcionalidades_obsoletas/index.html delete mode 100644 files/pt-pt/web/javascript/reference/funcoes/arguments/index.html delete mode 100644 files/pt-pt/web/javascript/reference/funcoes/funcoes_seta/index.html delete mode 100644 files/pt-pt/web/javascript/reference/funcoes/index.html delete mode 100644 files/pt-pt/web/javascript/reference/funcoes/parametros_rest/index.html create mode 100644 files/pt-pt/web/javascript/reference/functions/arguments/index.html create mode 100644 files/pt-pt/web/javascript/reference/functions/arrow_functions/index.html create mode 100644 files/pt-pt/web/javascript/reference/functions/index.html create mode 100644 files/pt-pt/web/javascript/reference/functions/rest_parameters/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/asyncfunction/prototype/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/number/prototype/index.html delete mode 100644 files/pt-pt/web/javascript/reference/global_objects/object/prototype/index.html delete mode 100644 "files/pt-pt/web/javascript/reference/operadores/fun\303\247\303\243o/index.html" delete mode 100644 files/pt-pt/web/javascript/reference/operadores/index.html delete mode 100644 files/pt-pt/web/javascript/reference/operadores/operador_virgula/index.html delete mode 100644 files/pt-pt/web/javascript/reference/operadores/precedencia_operador/index.html create mode 100644 files/pt-pt/web/javascript/reference/operators/comma_operator/index.html create mode 100644 files/pt-pt/web/javascript/reference/operators/function/index.html create mode 100644 files/pt-pt/web/javascript/reference/operators/index.html create mode 100644 files/pt-pt/web/javascript/reference/operators/operator_precedence/index.html delete mode 100644 files/pt-pt/web/javascript/reference/sobre/index.html create mode 100644 files/pt-pt/web/javascript/reference/statements/block/index.html create mode 100644 files/pt-pt/web/javascript/reference/statements/for/index.html create mode 100644 files/pt-pt/web/javascript/reference/statements/index.html create mode 100644 files/pt-pt/web/javascript/reference/statements/return/index.html create mode 100644 files/pt-pt/web/javascript/reference/statements/throw/index.html create mode 100644 files/pt-pt/web/javascript/shells/index.html (limited to 'files/pt-pt/web/javascript') diff --git a/files/pt-pt/web/javascript/data_structures/index.html b/files/pt-pt/web/javascript/data_structures/index.html new file mode 100644 index 0000000000..8b8578229b --- /dev/null +++ b/files/pt-pt/web/javascript/data_structures/index.html @@ -0,0 +1,297 @@ +--- +title: Tipos de dados de JavaScript e estruturas de dados +slug: Web/JavaScript/Estruturas_de_dados +tags: + - JavaScript + - Principiante + - Tipos +translation_of: Web/JavaScript/Data_structures +--- +
{{jsSidebar("More")}}
+ +

Programming languages all have built-in data structures, but these often differ from one language to another. This article attempts to list the built-in data structures available in JavaScript and what properties they have; these can be used to build other data structures. When possible, comparisons with other languages are drawn.

+ +

Digitação dinâmica

+ +

JavaScript is a loosely typed or a dynamic language. Variables in JavaScript are not directly associated with any particular value type, and any variable can be assigned (and re-assigned)  values of all types:

+ +
var foo = 42;    // foo is now a Number
+var foo = 'bar'; // foo is now a String
+var foo = true;  // foo is now a Boolean
+
+ +

Tipos de dados

+ +

The latest ECMAScript standard defines seven data types:

+ + + +

Valores primitivos

+ +

All types except objects define immutable values (values, which are incapable of being changed). For example and unlike to C, Strings are immutable. We refer to values of these types as "primitive values".

+ +

Tipo booleano

+ +

Boolean represents a logical entity and can have two values: true, and false.

+ +

Tipo Null

+ +

The Null type has exactly one value: null. See {{jsxref("null")}} and {{Glossary("Null")}} for more details.

+ +

Tipo indefinido

+ +

A variable that has not been assigned a value has the value undefined. See {{jsxref("undefined")}} and {{Glossary("Undefined")}} for more details.

+ +

Tipo número

+ +

According to the ECMAScript standard, there is only one number type: the double-precision 64-bit binary format IEEE 754 value (number between -(253 -1) and 253 -1). There is no specific type for integers. In addition to being able to represent floating-point numbers, the number type has three symbolic values: +Infinity, -Infinity, and NaN (not-a-number).

+ +

To check for the largest available value or smallest available value within +/-Infinity, you can use the constants {{jsxref("Number.MAX_VALUE")}} or {{jsxref("Number.MIN_VALUE")}} and starting with ECMAScript 6, you are also able to check if a number is in the double-precision floating-point number range using {{jsxref("Number.isSafeInteger()")}} as well as {{jsxref("Number.MAX_SAFE_INTEGER")}} and {{jsxref("Number.MIN_SAFE_INTEGER")}}. Beyond this range, integers in JavaScript are not safe anymore and will be a double-precision floating point approximation of the value.

+ +

The number type has only one integer that has two representations: 0 is represented as -0 and +0. ("0" is an alias for +0). In the praxis, this has almost no impact. For example +0 === -0 is true. However, you are able to notice this when you divide by zero:

+ +
> 42 / +0
+Infinity
+> 42 / -0
+-Infinity
+
+ +

Although a number often represents only its value, JavaScript provides some binary operators. These can be used to represent several Boolean values within a single number using bit masking. However, this is usually considered a bad practice, since JavaScript offers other means to represent a set of Booleans (like an array of Booleans or an object with Boolean values assigned to named properties). Bit masking also tends to make code more difficult to read, understand, and maintain. It may be necessary to use such techniques in very constrained environments, like when trying to cope with the storage limitation of local storage or in extreme cases when each bit over the network counts. This technique should only be considered when it is the last measure that can be taken to optimize size.

+ +

Tipo string

+ +

JavaScript's {{jsxref("Global_Objects/String", "String")}} type is used to represent textual data. It is a set of "elements" of 16-bit unsigned integer values. Each element in the String occupies a position in the String. The first element is at index 0, the next at index 1, and so on. The length of a String is the number of elements in it.

+ +

Unlike in languages like C, JavaScript strings are immutable. This means that once a string is created, it is not possible to modify it. However, it is still possible to create another string based on an operation on the original string. For example:

+ + + +

Beware of "stringly-typing" your code!

+ +

It can be tempting to use strings to represent complex data. Doing this comes with short-term benefits:

+ + + +

With conventions, it is possible to represent any data structure in a string. This does not make it a good idea. For instance, with a separator, one could emulate a list (while a JavaScript array would be more suitable). Unfortunately, when the separator is used in one of the "list" elements, then, the list is broken. An escape character can be chosen, etc. All of this requires conventions and creates an unnecessary maintenance burden.

+ +

Use strings for textual data. When representing complex data, parse strings and use the appropriate abstraction.

+ +

Tipo símbolo

+ +

Symbols are new to JavaScript in ECMAScript Edition 6. A Symbol is a unique and immutable primitive value and may be used as the key of an Object property (see below). In some programming languages, Symbols are called atoms. For more details see {{Glossary("Symbol")}} and the {{jsxref("Symbol")}} object wrapper in JavaScript.

+ +

Objetos

+ +

In computer science, an object is a value in memory which is possibly referenced by an {{Glossary("Identifier", "identifier")}}.

+ +

Propriedades

+ +

In JavaScript, objects can be seen as a collection of properties. With the object literal syntax, a limited set of properties are initialized; then properties can be added and removed. Property values can be values of any type, including other objects, which enables building complex data structures. Properties are identified using key values. A key value is either a String or a Symbol value.

+ +

There are two types of object properties which have certain attributes: The data property and the accessor property.

+ +

Data property

+ +

Associates a key with a value and has the following attributes:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Attributes of a data property
AttributeTypeDescriptionDefault value
[[Value]]Any JavaScript typeThe value retrieved by a get access of the property.undefined
[[Writable]]BooleanIf false, the property's [[Value]] can't be changed.false
[[Enumerable]]BooleanIf true, the property will be enumerated in for...in loops. See also Enumerability and ownership of propertiesfalse
[[Configurable]]BooleanIf false, the property can't be deleted and attributes other than [[Value]] and [[Writable]] can't be changed.false
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Obsolete attributes (as of ECMAScript 3, renamed in ECMAScript 5)
AttributeTypeDescription
Read-onlyBooleanReversed state of the ES5 [[Writable]] attribute.
DontEnumBooleanReversed state of the ES5 [[Enumerable]] attribute.
DontDeleteBooleanReversed state of the ES5 [[Configurable]] attribute.
+ +

Accessor property

+ +

Associates a key with one or two accessor functions (get and set) to retrieve or store a value and has the following attributes:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Attributes of an accessor property
AttributeTypeDescriptionDefault value
[[Get]]Function object or undefinedThe function is called with an empty argument list and retrieves the property value whenever a get access to the value is performed. See also get.undefined
[[Set]]Function object or undefinedThe function is called with an argument that contains the assigned value and is executed whenever a specified property is attempted to be changed. See also set.undefined
[[Enumerable]]BooleanIf true, the property will be enumerated in for...in loops.false
[[Configurable]]BooleanIf false, the property can't be deleted and can't be changed to a data property.false
+ +
+

Note: Attribute is usually used by JavaScript engine, so you can't directly access it(see more about Object.defineProperty()).That's why the attribute is put in double square brackets instead of single.

+
+ +

Objetos "Normal", e funções

+ +

A JavaScript object is a mapping between keys and values. Keys are strings (or {{jsxref("Symbol")}}s) and values can be anything. This makes objects a natural fit for hashmaps.

+ +

Functions are regular objects with the additional capability of being callable.

+ +

Dates

+ +

When representing dates, the best choice is to use the built-in Date utility in JavaScript.

+ +

Coleções indexadas: Arrays e Arrays digitados

+ +

Arrays are regular objects for which there is a particular relationship between integer-key-ed properties and the 'length' property. Additionally, arrays inherit from Array.prototype which provides to them a handful of convenient methods to manipulate arrays. For example, indexOf (searching a value in the array) or push (adding an element to the array), etc. This makes Arrays a perfect candidate to represent lists or sets.

+ +

Typed Arrays are new to JavaScript with ECMAScript Edition 6 and present an array-like view of an underlying binary data buffer. The following table helps you to find the equivalent C data types:

+ +

{{page("/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray", "TypedArray_objects", "", 0, 3)}}

+ +

Keyed collections: Maps, Sets, WeakMaps, WeakSets

+ +

These data structures take object references as keys and are introduced in ECMAScript Edition 6. {{jsxref("Set")}} and {{jsxref("WeakSet")}} represent a set of objects, while {{jsxref("Map")}} and {{jsxref("WeakMap")}} associate a value to an object. The difference between Maps and WeakMaps is that in the former, object keys can be enumerated over. This allows garbage collection optimizations in the latter case.

+ +

One could implement Maps and Sets in pure ECMAScript 5. However, since objects cannot be compared (in the sense of "less than" for instance), look-up performance would necessarily be linear. Native implementations of them (including WeakMaps) can have look-up performance that is approximately logarithmic to constant time.

+ +

Usually, to bind data to a DOM node, one could set properties directly on the object or use data-* attributes. This has the downside that the data is available to any script running in the same context. Maps and WeakMaps make it easy to privately bind data to an object.

+ +

Structured data: JSON

+ +

JSON (JavaScript Object Notation) is a lightweight data-interchange format, derived from JavaScript but used by many programming languages. JSON builds universal data structures. See {{Glossary("JSON")}} and {{jsxref("JSON")}} for more details.

+ +

More objects in the standard library

+ +

JavaScript has a standard library of built-in objects. Please have a look at the reference to find out about more objects.

+ +

Determining types using the typeof operator

+ +

The typeof operator can help you to find the type of your variable. Please read the reference page for more details and edge cases.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-8', 'Types')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-ecmascript-data-types-and-values', 'ECMAScript Data Types and Values')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-ecmascript-data-types-and-values', 'ECMAScript Data Types and Values')}}{{Spec2('ESDraft')}} 
+ +

Consulte também

+ + diff --git a/files/pt-pt/web/javascript/estruturas_de_dados/index.html b/files/pt-pt/web/javascript/estruturas_de_dados/index.html deleted file mode 100644 index 8b8578229b..0000000000 --- a/files/pt-pt/web/javascript/estruturas_de_dados/index.html +++ /dev/null @@ -1,297 +0,0 @@ ---- -title: Tipos de dados de JavaScript e estruturas de dados -slug: Web/JavaScript/Estruturas_de_dados -tags: - - JavaScript - - Principiante - - Tipos -translation_of: Web/JavaScript/Data_structures ---- -
{{jsSidebar("More")}}
- -

Programming languages all have built-in data structures, but these often differ from one language to another. This article attempts to list the built-in data structures available in JavaScript and what properties they have; these can be used to build other data structures. When possible, comparisons with other languages are drawn.

- -

Digitação dinâmica

- -

JavaScript is a loosely typed or a dynamic language. Variables in JavaScript are not directly associated with any particular value type, and any variable can be assigned (and re-assigned)  values of all types:

- -
var foo = 42;    // foo is now a Number
-var foo = 'bar'; // foo is now a String
-var foo = true;  // foo is now a Boolean
-
- -

Tipos de dados

- -

The latest ECMAScript standard defines seven data types:

- - - -

Valores primitivos

- -

All types except objects define immutable values (values, which are incapable of being changed). For example and unlike to C, Strings are immutable. We refer to values of these types as "primitive values".

- -

Tipo booleano

- -

Boolean represents a logical entity and can have two values: true, and false.

- -

Tipo Null

- -

The Null type has exactly one value: null. See {{jsxref("null")}} and {{Glossary("Null")}} for more details.

- -

Tipo indefinido

- -

A variable that has not been assigned a value has the value undefined. See {{jsxref("undefined")}} and {{Glossary("Undefined")}} for more details.

- -

Tipo número

- -

According to the ECMAScript standard, there is only one number type: the double-precision 64-bit binary format IEEE 754 value (number between -(253 -1) and 253 -1). There is no specific type for integers. In addition to being able to represent floating-point numbers, the number type has three symbolic values: +Infinity, -Infinity, and NaN (not-a-number).

- -

To check for the largest available value or smallest available value within +/-Infinity, you can use the constants {{jsxref("Number.MAX_VALUE")}} or {{jsxref("Number.MIN_VALUE")}} and starting with ECMAScript 6, you are also able to check if a number is in the double-precision floating-point number range using {{jsxref("Number.isSafeInteger()")}} as well as {{jsxref("Number.MAX_SAFE_INTEGER")}} and {{jsxref("Number.MIN_SAFE_INTEGER")}}. Beyond this range, integers in JavaScript are not safe anymore and will be a double-precision floating point approximation of the value.

- -

The number type has only one integer that has two representations: 0 is represented as -0 and +0. ("0" is an alias for +0). In the praxis, this has almost no impact. For example +0 === -0 is true. However, you are able to notice this when you divide by zero:

- -
> 42 / +0
-Infinity
-> 42 / -0
--Infinity
-
- -

Although a number often represents only its value, JavaScript provides some binary operators. These can be used to represent several Boolean values within a single number using bit masking. However, this is usually considered a bad practice, since JavaScript offers other means to represent a set of Booleans (like an array of Booleans or an object with Boolean values assigned to named properties). Bit masking also tends to make code more difficult to read, understand, and maintain. It may be necessary to use such techniques in very constrained environments, like when trying to cope with the storage limitation of local storage or in extreme cases when each bit over the network counts. This technique should only be considered when it is the last measure that can be taken to optimize size.

- -

Tipo string

- -

JavaScript's {{jsxref("Global_Objects/String", "String")}} type is used to represent textual data. It is a set of "elements" of 16-bit unsigned integer values. Each element in the String occupies a position in the String. The first element is at index 0, the next at index 1, and so on. The length of a String is the number of elements in it.

- -

Unlike in languages like C, JavaScript strings are immutable. This means that once a string is created, it is not possible to modify it. However, it is still possible to create another string based on an operation on the original string. For example:

- - - -

Beware of "stringly-typing" your code!

- -

It can be tempting to use strings to represent complex data. Doing this comes with short-term benefits:

- - - -

With conventions, it is possible to represent any data structure in a string. This does not make it a good idea. For instance, with a separator, one could emulate a list (while a JavaScript array would be more suitable). Unfortunately, when the separator is used in one of the "list" elements, then, the list is broken. An escape character can be chosen, etc. All of this requires conventions and creates an unnecessary maintenance burden.

- -

Use strings for textual data. When representing complex data, parse strings and use the appropriate abstraction.

- -

Tipo símbolo

- -

Symbols are new to JavaScript in ECMAScript Edition 6. A Symbol is a unique and immutable primitive value and may be used as the key of an Object property (see below). In some programming languages, Symbols are called atoms. For more details see {{Glossary("Symbol")}} and the {{jsxref("Symbol")}} object wrapper in JavaScript.

- -

Objetos

- -

In computer science, an object is a value in memory which is possibly referenced by an {{Glossary("Identifier", "identifier")}}.

- -

Propriedades

- -

In JavaScript, objects can be seen as a collection of properties. With the object literal syntax, a limited set of properties are initialized; then properties can be added and removed. Property values can be values of any type, including other objects, which enables building complex data structures. Properties are identified using key values. A key value is either a String or a Symbol value.

- -

There are two types of object properties which have certain attributes: The data property and the accessor property.

- -

Data property

- -

Associates a key with a value and has the following attributes:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Attributes of a data property
AttributeTypeDescriptionDefault value
[[Value]]Any JavaScript typeThe value retrieved by a get access of the property.undefined
[[Writable]]BooleanIf false, the property's [[Value]] can't be changed.false
[[Enumerable]]BooleanIf true, the property will be enumerated in for...in loops. See also Enumerability and ownership of propertiesfalse
[[Configurable]]BooleanIf false, the property can't be deleted and attributes other than [[Value]] and [[Writable]] can't be changed.false
- - - - - - - - - - - - - - - - - - - - - - - - - -
Obsolete attributes (as of ECMAScript 3, renamed in ECMAScript 5)
AttributeTypeDescription
Read-onlyBooleanReversed state of the ES5 [[Writable]] attribute.
DontEnumBooleanReversed state of the ES5 [[Enumerable]] attribute.
DontDeleteBooleanReversed state of the ES5 [[Configurable]] attribute.
- -

Accessor property

- -

Associates a key with one or two accessor functions (get and set) to retrieve or store a value and has the following attributes:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Attributes of an accessor property
AttributeTypeDescriptionDefault value
[[Get]]Function object or undefinedThe function is called with an empty argument list and retrieves the property value whenever a get access to the value is performed. See also get.undefined
[[Set]]Function object or undefinedThe function is called with an argument that contains the assigned value and is executed whenever a specified property is attempted to be changed. See also set.undefined
[[Enumerable]]BooleanIf true, the property will be enumerated in for...in loops.false
[[Configurable]]BooleanIf false, the property can't be deleted and can't be changed to a data property.false
- -
-

Note: Attribute is usually used by JavaScript engine, so you can't directly access it(see more about Object.defineProperty()).That's why the attribute is put in double square brackets instead of single.

-
- -

Objetos "Normal", e funções

- -

A JavaScript object is a mapping between keys and values. Keys are strings (or {{jsxref("Symbol")}}s) and values can be anything. This makes objects a natural fit for hashmaps.

- -

Functions are regular objects with the additional capability of being callable.

- -

Dates

- -

When representing dates, the best choice is to use the built-in Date utility in JavaScript.

- -

Coleções indexadas: Arrays e Arrays digitados

- -

Arrays are regular objects for which there is a particular relationship between integer-key-ed properties and the 'length' property. Additionally, arrays inherit from Array.prototype which provides to them a handful of convenient methods to manipulate arrays. For example, indexOf (searching a value in the array) or push (adding an element to the array), etc. This makes Arrays a perfect candidate to represent lists or sets.

- -

Typed Arrays are new to JavaScript with ECMAScript Edition 6 and present an array-like view of an underlying binary data buffer. The following table helps you to find the equivalent C data types:

- -

{{page("/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray", "TypedArray_objects", "", 0, 3)}}

- -

Keyed collections: Maps, Sets, WeakMaps, WeakSets

- -

These data structures take object references as keys and are introduced in ECMAScript Edition 6. {{jsxref("Set")}} and {{jsxref("WeakSet")}} represent a set of objects, while {{jsxref("Map")}} and {{jsxref("WeakMap")}} associate a value to an object. The difference between Maps and WeakMaps is that in the former, object keys can be enumerated over. This allows garbage collection optimizations in the latter case.

- -

One could implement Maps and Sets in pure ECMAScript 5. However, since objects cannot be compared (in the sense of "less than" for instance), look-up performance would necessarily be linear. Native implementations of them (including WeakMaps) can have look-up performance that is approximately logarithmic to constant time.

- -

Usually, to bind data to a DOM node, one could set properties directly on the object or use data-* attributes. This has the downside that the data is available to any script running in the same context. Maps and WeakMaps make it easy to privately bind data to an object.

- -

Structured data: JSON

- -

JSON (JavaScript Object Notation) is a lightweight data-interchange format, derived from JavaScript but used by many programming languages. JSON builds universal data structures. See {{Glossary("JSON")}} and {{jsxref("JSON")}} for more details.

- -

More objects in the standard library

- -

JavaScript has a standard library of built-in objects. Please have a look at the reference to find out about more objects.

- -

Determining types using the typeof operator

- -

The typeof operator can help you to find the type of your variable. Please read the reference page for more details and edge cases.

- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-8', 'Types')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-ecmascript-data-types-and-values', 'ECMAScript Data Types and Values')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-ecmascript-data-types-and-values', 'ECMAScript Data Types and Values')}}{{Spec2('ESDraft')}} 
- -

Consulte também

- - diff --git a/files/pt-pt/web/javascript/gestao_memoria/index.html b/files/pt-pt/web/javascript/gestao_memoria/index.html deleted file mode 100644 index 56bfec0f7f..0000000000 --- a/files/pt-pt/web/javascript/gestao_memoria/index.html +++ /dev/null @@ -1,187 +0,0 @@ ---- -title: Gestão de memória -slug: Web/JavaScript/Gestao_Memoria -tags: - - Desempenho - - JavaScript - - memoria -translation_of: Web/JavaScript/Memory_Management ---- -
{{JsSidebar("Advanced")}}
- -

Introdução

- -

Linguagens de baixo nível, como o C, têm funções pimitivas de gestão de memória, como por exemplo, malloc() e free(). Por outro lado, os valores em JavaScript são alocados quando coisas (objetos, variáveis de texto, etc.) são criadas e "automaticamente" libertadas da memória quando deixam de ser utilizadas. O último processo é chamado de coleção do lixo. Este "automatismo" é uma fonte de mal entendidos e transmite aos programadores de JavaScript ( e aos de outras linguagens de alto nível ) a impressão de que podem decidir não se preocupar com a gestão da memória. Isto é uma erro.

- -

Ciclo da duração da memória

- -

Independentemente da linguagem de programação, o ciclo da duração da memória é praticamente sempre o mesmo:

- -
    -
  1. Alocação da memória necessária
  2. -
  3. Utilização da memória alocada ( leitura, escrita )
  4. -
  5. Libertar a memória alocada quando já não é necessária
  6. -
- -

A segunda etapa é explícita em todas as linguagens. A primeira e a última etapa são explícitas em linguagens de baixo nível mas são, na sua maioria, implícitas em linguagens de alto nível como o JavaScript.

- -

Alocação no JavaScript

- -

Inicialização do valor

- -

Com o intuito de não incomodar o programador com alocações, o JavaScript fá-lo juntamente com a declaração de valores.

- -
var n = 123; // alocação da memória para um número
-var s = 'azerty'; // alocação de memória para um texto
-
-var o = {
-  a: 1,
-  b: null
-}; // alocação de memória para um objeto e o seu conteúdo
-
-// (similar ao objeto) alocação de memória para a matriz e
-// os seus valores
-var a = [1, null, 'abra'];
-
-function f(a) {
-  return a + 2;
-} // alocação de uma função (que é um objeto que pode ser chamado)
-
-// Expressões de funções também alocam um objeto
-someElement.addEventListener('click', function() {
-  someElement.style.backgroundColor = 'blue';
-}, false);
-
- -

Alocação através de chamadas de funções

- -

Algumas chamadas de funções resultam na alocação de um objeto.

- -
var d = new Date(); // alocação de um objeto Date
-
-var e = document.createElement('div'); // alocação de um elemento DOM
- -

Alguns métodos alocam novos valores ou objetos:

- -
var s = 'azerty';
-var s2 = s.substr(0, 3); // s2 é uma nova variável de texto
-// Dado que as variáveis de texto são de valor imutável,
-// o JavaScript pode decidir não alocar memória,
-// mas apenas armazenar o intervalo [0, 3].
-
-var a = ['ouais ouais', 'nan nan'];
-var a2 = ['generation', 'nan nan'];
-var a3 = a.concat(a2);
-// nova matriz de 4 elementos resultando
-// da concatenação dos elementos de a e a2
-
- -

Utilização de valores

- -

Basicamente, a utilização de valores significa a leitura e a escrita na memória alocada. Isto pode ser feito através da leitura ou escrita do valor de uma variável ou uma propriedade de um objeto ou até a passagem de um argumento para uma função.

- -

Remoção quando a memória já não é necessária

- -

A maioria dos problemas de gestão de memória aparecem nesta fase. A tarefa mais difícil é descobrir quando "a memória alocada já não é necessária". Em geral, requer que o programador determine quando, no seu código, este pedaço de memória já não é necessário e a liberte.

- -

Linguagens de alto nível têm embutidas um pedaço de código chamado "coleção de lixo", cuja tarefa é rastrear a alocação e uso da memória, para detetar quando um pedaço de memória já não é necessário e neste caso, automaticamente libertá-la. Este processo é uma aproximação dado que o problema geral de se saber quando um pedaço da memória é necessário, é indecisível ( não pode ser solucionado por um algoritmo ).

- -

Coleção de lixo

- -

Como mencionado anteriormente, o problema geral de automaticamente descobrir quando alguma ocupação de memória "já não é necessária", é indecisível. Como consequência, as coleções de lixo implementam uma restrição à solução para o problema em geral. Esta seção explicará as noções necessárias para se compreender os principais algoritmos da coleção de lixo e as suas limitações.

- -

Referências

- -

A noção principal dos algoritmos de coleção de lixo baseiam-se na noção de referência. Dentro do contexto da gestão de memória, um objeto é dito referenciar outro objeto, se o primeiro tiver acesso ao segundo ( quer implicitamente quer explicitamente ). Por exemplo, um objeto JavaScript tem uma referência ao seu protótipo ( referência implícita )  e aos valores das suas propriedades ( referência explícita ).

- -

Neste contexto, a noção de "objeto" é expandida a algo mais abrangente que um objeto JavaScript e também contém âmbitos de funções ( ou âmbito léxico global ).

- -

Contagem de referências na coleção de lixo

- -

Este é o algoritmo mais simples da coleção de lixo. Este algoritmo reduz a definição de "um objeto já não é necessário" para "um objeto já não é referenciado por nenhum outro objeto". Um objeto é considerado coletável para a coleção de lixo se tiver nenhuma referenciação por parte de outro objeto.

- -

Exemplo

- -
var o = {
-  a: {
-    b: 2
-  }
-};
-// 2 objetos criados. Um é referenciado por outro como sendo suas propriedades
-// O outro é referenciado por virtude ao ser assignado para a variável 'o'
-// Obviamente, nenhum podem ser coletado pela coleção de lixo
-
-
-var o2 = o; // A variável 'o2' é a segunda coisa que
-            // tem uma referência ao objeto
-o = 1;      // agora, o objeto que era originalmente o 'o' tem uma referência única
-            // corporificada pela variável 'o2'
-
-var oa = o2.a; // referência à propriedade 'a' do objeto.
-               // Este objeto tem agora 2 referências: uma como propriedade,
-               // a outra como variável 'oa'
-
-o2 = 'yo'; // O objeto que era o original 'o' tem agora zero
-           // referências a si próprio. Pode ser coletado para a coleção de lixo
-           // No entanto, a propriedade 'a' ainda é referenciada pela
-           // variável 'oa', logo não pode ser libertado
-
-oa = null; // A propriedade 'a' do objeto original 'o'
-           // tem zero referências a si próprio. Pode ser coletado para a  coleção de lixo.
-
- -

Limitação: ciclos

- -

Existe uma limitação no que se refere aos ciclos. No exemplo seguinte, dois objetos são criados e referenciam-se mutuamente, criando um ciclo. Estes sairão do âmbito depois de uma chamada a uma função e como tal, são efetivamente inúteis e podem ser libertados. No entanto, o algoritmo de contagem de referências considera que os dois objetos têm pelo menos uma referenciação; nenhum pode ser coletado para a coleção de lixo .

- -
function f() {
-  var o = {};
-  var o2 = {};
-  o.a = o2; // o referencia o2
-  o2.a = o; // o2 referencia o
-
-  return 'azerty';
-}
-
-f();
-
- -

Exemplo de aplicação real

- -

O Internet Explorer 6 e 7 são conhecidos por terem um coletor de contagem de referenciações de coleções de lixo para os objetos DOM. Os ciclos são um erro comum que podem gerar percas de memória:

- -
var div;
-window.onload = function() {
-  div = document.getElementById('myDivElement');
-  div.circularReference = div;
-  div.lotsOfData = new Array(10000).join('*');
-};
-
- -

No exemplo acima, o elemento DOM "myDivElement" tem uma referência circular a si próprio na propriedade "circularReference". Se a propriedade não for explicitamente removida ou anulada, o coletor de contagem de referências da coleção de lixo, irá sempre ter uma referenciação intacta e irá manter o elemento DOM na memória mesmo quando for removido da árvore DOM. Se o elemento DOM contém bastante dados ( ilustrado no exemplo acima com a propriedade "lotsOfData" ), a memória consumida por estes dados nunca será libertada.

- -

Algoritmo de marcação e limpeza

- -

Este algoritmo reduz a definição de "um objeto já não é necessário" para "um objeto é inalcançável".

- -

Este algoritmo assume o conhecimento de um conjunto de objetos chamados "roots" ( em JavaScript, a root - raiz - é um objeto global ). Periodicamente, a coleção de lixo começará pela raíz e procurará todos os objetos que são referenciados a partir desta; depois todos os que são referenciados a partir dos seguintes, etc.. Começando pela raiz, o coletor de lixo irá localizar objetos inalcançáveis; coletando-os.

- -

Este algoritmo é melhor do que o anterior dado que "um objeto tem zero referenciações" leva a um objeto inalcançável. O contrário não é verdade como vimos nos ciclos.

- -

Desde 2012, todos os modernos navegadores de Internet contêm um coletor de marcação e limpeza. Todos os melhoramentos feitos na área da coleção de lixo no JavaScript ( generalização / incrementação / concorrência / coleção de lixo paralela ) nos últimos anos são implemetações de melhoramento deste algoritmo, mas não melhoramentos do algoritmo de coleção de lixo em si nem a sua redução à definição de que quando "um objeto já não é necessário".

- -

Os ciclos já não são um problema.

- -

No primeiro exemplo acima, depois do retorno da chamada à função, 2 objetos já não são referenciados por algo alcançável no objeto global. Consequentemente, irão ser localizados pelo coletor da coleção de lixo.

- -

Limitações: os objetos necessitam de ser explicitamente inalcançáveis

- -

Apesar disto estar marcado como uma limitação, é um caso que raramente ocorre na prática pelo que é por isto que ninguém se preocupa muito com a coleção de lixo.

- -

Ver também

- - 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 ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Working_with_Objects", "Web/JavaScript/Guide/Iterators_and_Generators")}}
- -
-

The content of this article is under discussion. Please provide feedback and help us to make this page better: {{bug(1201380)}}.

-
- -

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.

- -

This chapter assumes that you are already somewhat familiar with JavaScript and that you have used JavaScript functions to create simple objects.

- -

Linguagens com base em classe versus protótipo

- -

Class-based object-oriented languages, such as Java and C++, are founded on the concept of two distinct entities: classes and instances.

- - - -

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 prototypical object, 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 prototype for another object, allowing the second object to share the first object's properties.

- -

Definição de uma classe

- -

In class-based languages, you define a class in a separate class definition. In that definition you can specify special methods, called constructors, 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 new operator in association with the constructor method to create class instances.

- -

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 new operator with a constructor function to create a new object.

- -

Subclasses e sucessão

- -

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 subclass 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 Employee class includes only the name and dept properties, and Manager is a subclass of Employee that adds the reports property. In this case, an instance of the Manager class would have all three properties: name, dept, and reports.

- -

JavaScript implements inheritance by allowing you to associate a prototypical object with any constructor function. So, you can create exactly the EmployeeManager example, but you use slightly different terminology. First you define the Employee constructor function, specifying the name and dept properties. Next, you define the Manager constructor function, calling the Employee constructor and specifying the reports property. Finally, you assign a new object derived from Employee.prototype as the prototype for the Manager constructor function. Then, when you create a new Manager, it inherits the name and dept properties from the Employee object.

- -

Adição e remoção de propriedades

- -

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.

- -

Resumo das diferenças

- -

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.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Comparison of class-based (Java) and prototype-based (JavaScript) object systems
Com base em Classe (Java)Com base em Protótipo (JavaScript)
Class and instance are distinct entities.All objects can inherit from another object.
Define a class with a class definition; instantiate a class with constructor methods.Define and create a set of objects with constructor functions.
Create a single object with the new operator.Same.
Construct an object hierarchy by using class definitions to define subclasses of existing classes.Construct an object hierarchy by assigning an object as the prototype associated with a constructor function.
Inherit properties by following the class chain.Inherit properties by following the prototype chain.
Class definition specifies all properties of all instances of a class. Cannot add properties dynamically at run time.Constructor function or prototype specifies an initial set of properties. Can add or remove properties dynamically to individual objects or to the entire set of objects.
- -

The employee example

- -

The remainder of this chapter uses the employee hierarchy shown in the following figure.

- -
-
-

A simple object hierarchy with the following objects:

- -

-
- -
-
    -
  • Employee has the properties name (whose value defaults to the empty string) and dept (whose value defaults to "general").
  • -
  • Manager is based on Employee. It adds the reports property (whose value defaults to an empty array, intended to have an array of Employee objects as its value).
  • -
  • WorkerBee is also based on Employee. It adds the projects property (whose value defaults to an empty array, intended to have an array of strings as its value).
  • -
  • SalesPerson is based on WorkerBee. It adds the quota property (whose value defaults to 100). It also overrides the dept property with the value "sales", indicating that all salespersons are in the same department.
  • -
  • Engineer is based on WorkerBee. It adds the machine property (whose value defaults to the empty string) and also overrides the dept property with the value "engineering".
  • -
-
-
- -

Criação de hierarquia

- -

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.

- -

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.

- -

In a real application, you would probably define constructors that allow you to provide property values at object creation time (see More flexible constructors for information). For now, these simple definitions demonstrate how the inheritance occurs.

- -

The following Java and JavaScript Employee 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 strongly typed language while JavaScript is a weakly typed language).

- -
-

JavaScript

- -
function Employee() {
-  this.name = "";
-  this.dept = "general";
-}
-
- -

Java

- -
public class Employee {
-   public String name = "";
-   public String dept = "general";
-}
-
-
- -

The Manager and WorkerBee 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 prototype 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.

- -
-

JavaScript

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

Java

- -
public class Manager extends Employee {
-   public Employee[] reports = new Employee[0];
-}
-
-
-
-public class WorkerBee extends Employee {
-   public String[] projects = new String[0];
-}
-
-
-
-
- -

The Engineer and SalesPerson definitions create objects that descend from WorkerBee and hence from Employee. 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 dept property with new values specific to these objects.

- -
-

JavaScript

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

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 = "";
-}
-
-
-
- -

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.

- -
-

Nota: The term instance 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 jane is an instance of Engineer. Similarly, although the terms parent, child, ancestor, and descendant do not have formal meanings in JavaScript; you can use them informally to refer to objects higher or lower in the prototype chain.

-
- -

Criação de objetos com definições simples

- -
-

Hierarquia do objeto

- -

The following hierarchy is created using the code on the right side.

- -

- -

 

- -

individual objects

- -
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 ''
-
-
- -

Propriedades do objeto

- -

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.

- -

Propriedades de sucessão

- -

Suppose you create the mark object as a WorkerBee with the following statement:

- -
var mark = new WorkerBee;
-
- -

When JavaScript sees the new operator, it creates a new generic object and passes this new object as the value of the this keyword to the WorkerBee constructor function. The constructor function explicitly sets the value of the projects property, and implicitly sets the value of the internal __proto__ property to the value of WorkerBee.prototype. (That property name has two underscore characters at the front and two at the end.) The __proto__ 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 mark to that object.

- -

This process does not explicitly put values in the mark object (local values) for the properties that mark 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 __proto__ 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 mark object has the following properties and values:

- -
mark.name = "";
-mark.dept = "general";
-mark.projects = [];
-
- -

The mark object inherits values for the name and dept properties from the prototypical object in mark.__proto__. It is assigned a local value for the projects property by the WorkerBee constructor. This gives you inheritance of properties and their values in JavaScript. Some subtleties of this process are discussed in Property inheritance revisited.

- -

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 WorkerBee. You can, of course, change the values of any of these properties. So, you could give specific information for mark as follows:

- -
mark.name = "Doe, Mark";
-mark.dept = "admin";
-mark.projects = ["navigator"];
- -

Adição de propriedades

- -

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:

- -
mark.bonus = 3000;
-
- -

Now, the mark object has a bonus property, but no other WorkerBee has this property.

- -

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 specialty property to all employees with the following statement:

- -
Employee.prototype.specialty = "none";
-
- -

As soon as JavaScript executes this statement, the mark object also has the specialty property with the value of "none". The following figure shows the effect of adding this property to the Employee prototype and then overriding it for the Engineer prototype.

- -


- Adding properties

- -

Mais construtores flexíveis

- -

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.

- -


- Specifying properties in a constructor, take 1

- -

The following table shows the Java and JavaScript definitions for these objects.

- -
-

JavaScript

- -

Java

-
- -
-
function Employee (name, dept) {
-  this.name = name || "";
-  this.dept = dept || "general";
-}
-
- -

 

- -

 

- -

 

- -

 

- -

 

- -
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;
-   }
-}
-
-
- -
-
function WorkerBee (projs) {
-
- this.projects = projs || [];
-}
-WorkerBee.prototype = new Employee;
-
- -

 

- -

 

- -

 

- -
public class WorkerBee extends Employee {
-   public String[] projects;
-   public WorkerBee () {
-      this(new String[0]);
-   }
-   public WorkerBee (String[] projs) {
-      projects = projs;
-   }
-}
-
-
- -
-
-function Engineer (mach) {
-   this.dept = "engineering";
-   this.machine = mach || "";
-}
-Engineer.prototype = new WorkerBee;
-
- -

 

- -

 

- -

 

- -
public class Engineer extends WorkerBee {
-   public String machine;
-   public Engineer () {
-      dept = "engineering";
-      machine = "";
-   }
-   public Engineer (String mach) {
-      dept = "engineering";
-      machine = mach;
-   }
-}
-
-
- -

These JavaScript definitions use a special idiom for setting default values:

- -
this.name = name || "";
-
- -

The JavaScript logical OR operator (||) 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 name has a useful value for the name property. If it does, it sets this.name to that value. Otherwise, it sets this.name to the empty string. This chapter uses this idiom for brevity; however, it can be puzzling at first glance.

- -
-

Note: This may not work as expected if the constructor function is called with arguments which convert to false (like 0 (zero) and empty string (""). In this case the default value will be chosen.

-
- -

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 Engineer:

- -
var jane = new Engineer("belau");
-
- -

Jane's properties are now:

- -
jane.name == "";
-jane.dept == "engineering";
-jane.projects == [];
-jane.machine == "belau"
-
- -

Notice that with these definitions, you cannot specify an initial value for an inherited property such as name. If you want to specify an initial value for inherited properties in JavaScript, you need to add more code to the constructor function.

- -

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.

- -


- Specifying properties in a constructor, take 2

- -

Let's look at one of these definitions in detail. Here's the new definition for the Engineer constructor:

- -
function Engineer (name, projs, mach) {
-  this.base = WorkerBee;
-  this.base(name, "engineering", projs);
-  this.machine = mach || "";
-}
-
- -

Suppose you create a new Engineer object as follows:

- -
var jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau");
-
- -

JavaScript follows these steps:

- -
    -
  1. The new operator creates a generic object and sets its __proto__ property to Engineer.prototype.
  2. -
  3. The new operator passes the new object to the Engineer constructor as the value of the this keyword.
  4. -
  5. The constructor creates a new property called base for that object and assigns the value of the WorkerBee constructor to the base property. This makes the WorkerBee constructor a method of the Engineer object.The name of the base property is not special. You can use any legal property name; base is simply evocative of its purpose.
  6. -
  7. -

    The constructor calls the base method, passing as its arguments two of the arguments passed to the constructor ("Doe, Jane" and ["navigator", "javascript"]) and also the string "engineering". Explicitly using "engineering" in the constructor indicates that all Engineer objects have the same value for the inherited dept property, and this value overrides the value inherited from Employee.

    -
  8. -
  9. Because base is a method of Engineer, within the call to base, JavaScript binds the this keyword to the object created in Step 1. Thus, the WorkerBee function in turn passes the "Doe, Jane" and "engineering" arguments to the Employee constructor function. Upon return from the Employee constructor function, the WorkerBee function uses the remaining argument to set the projects property.
  10. -
  11. Upon return from the base method, the Engineer constructor initializes the object's machine property to "belau".
  12. -
  13. Upon return from the constructor, JavaScript assigns the new object to the jane variable.
  14. -
- -

You might think that, having called the WorkerBee constructor from inside the Engineer constructor, you have set up inheritance appropriately for Engineer objects. This is not the case. Calling the WorkerBee constructor ensures that an Engineer object starts out with the properties specified in all constructor functions that are called. However, if you later add properties to the Employee or WorkerBee prototypes, those properties are not inherited by the Engineer object. For example, assume you have the following statements:

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

The jane object does not inherit the specialty property. You still need to explicitly set up the prototype to ensure dynamic inheritance. Assume instead you have these statements:

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

Now the value of the jane object's specialty property is "none".

- -

Another way of inheriting is by using the call() / apply() methods. Below are equivalent:

- -
-
function Engineer (name, projs, mach) {
-  this.base = WorkerBee;
-  this.base(name, "engineering", projs);
-  this.machine = mach || "";
-}
-
- -
function Engineer (name, projs, mach) {
-  WorkerBee.call(this, name, "engineering", projs);
-  this.machine = mach || "";
-}
-
-
- -

Using the javascript call() method makes a cleaner implementation because the base is not needed anymore.

- -

Sucessão de propriedade revisitada

- -

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.

- -

Valores locais versus sucedidos

- -

When you access an object property, JavaScript performs these steps, as described earlier in this chapter:

- -
    -
  1. Check to see if the value exists locally. If it does, return that value.
  2. -
  3. If there is not a local value, check the prototype chain (using the __proto__ property).
  4. -
  5. If an object in the prototype chain has a value for the specified property, return that value.
  6. -
  7. If no such property is found, the object does not have the property.
  8. -
- -

The outcome of these steps depends on how you define things along the way. The original example had these definitions:

- -
function Employee () {
-  this.name = "";
-  this.dept = "general";
-}
-
-function WorkerBee () {
-  this.projects = [];
-}
-WorkerBee.prototype = new Employee;
-
- -

With these definitions, suppose you create amy as an instance of WorkerBee with the following statement:

- -
var amy = new WorkerBee;
-
- -

The amy object has one local property, projects. The values for the name and dept properties are not local to amy and so derive from the amy object's __proto__ property. Thus, amy has these property values:

- -
amy.name == "";
-amy.dept == "general";
-amy.projects == [];
-
- -

Now suppose you change the value of the name property in the prototype associated with Employee:

- -
Employee.prototype.name = "Unknown"
-
- -

At first glance, you might expect that new value to propagate down to all the instances of Employee. However, it does not.

- -

When you create any instance of the Employee object, that instance gets a local value for the name property (the empty string). This means that when you set the WorkerBee prototype by creating a new Employee object, WorkerBee.prototype has a local value for the name property. Therefore, when JavaScript looks up the name property of the amy object (an instance of WorkerBee), JavaScript finds the local value for that property in WorkerBee.prototype. It therefore does not look further up the chain to Employee.prototype.

- -

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:

- -
function Employee () {
-  this.dept = "general";
-}
-Employee.prototype.name = "";
-
-function WorkerBee () {
-  this.projects = [];
-}
-WorkerBee.prototype = new Employee;
-
-var amy = new WorkerBee;
-
-Employee.prototype.name = "Unknown";
-
- -

In this case, the name property of amy becomes "Unknown".

- -

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.

- -

Determining instance relationships

- -

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 __proto__. This continues recursively; the process is called "lookup in the prototype chain".

- -

The special property __proto__ is set when an object is constructed; it is set to the value of the constructor's prototype property. So the expression new Foo() creates an object with __proto__ == Foo.prototype. Consequently, changes to the properties of Foo.prototype alters the property lookup for all objects that were created by new Foo().

- -

Every object has a __proto__ object property (except Object); every function has a prototype object property. So objects can be related by 'prototype inheritance' to other objects. You can test for inheritance by comparing an object's __proto__ to a function's prototype object. JavaScript provides a shortcut: the instanceof operator tests an object against a function and returns true if the object inherits from the function prototype. For example,

- -
var f = new Foo();
-var isTrue = (f instanceof Foo);
- -

For a more detailed example, suppose you have the same set of definitions shown in Inheriting properties. Create an Engineer object as follows:

- -
var chris = new Engineer("Pigman, Chris", ["jsd"], "fiji");
-
- -

With this object, the following statements are all true:

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

Given this, you could write an instanceOf function as follows:

- -
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;
-}
-
- -
Note: 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.
- -

Using the instanceOf function defined above, these expressions are true:

- -
instanceOf (chris, Engineer)
-instanceOf (chris, WorkerBee)
-instanceOf (chris, Employee)
-instanceOf (chris, Object)
-
- -

But the following expression is false:

- -
instanceOf (chris, SalesPerson)
-
- -

Informação global nos construtores

- -

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 Employee:

- -
var idCounter = 1;
-
-function Employee (name, dept) {
-   this.name = name || "";
-   this.dept = dept || "general";
-   this.id = idCounter++;
-}
-
- -

With this definition, when you create a new Employee, the constructor assigns it the next ID in sequence and then increments the global ID counter. So, if your next statement is the following, victoria.id is 1 and harry.id is 2:

- -
var victoria = new Employee("Pigbert, Victoria", "pubs")
-var harry = new Employee("Tschopik, Harry", "sales")
-
- -

At first glance that seems fine. However, idCounter gets incremented every time an Employee object is created, for whatever purpose. If you create the entire Employee hierarchy shown in this chapter, the Employee constructor is called every time you set up a prototype. Suppose you have the following code:

- -
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");
-
- -

Further assume that the definitions omitted here have the base property and call the constructor above them in the prototype chain. In this case, by the time the mac object is created, mac.id is 5.

- -

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:

- -
function Employee (name, dept) {
-   this.name = name || "";
-   this.dept = dept || "general";
-   if (name)
-      this.id = idCounter++;
-}
-
- -

When you create an instance of Employee 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 Employee to get an assigned id, you must specify a name for the employee. In this example, mac.id would be 1.

- -

No multiple inheritance

- -

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.

- -

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.

- -

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:

- -
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")
-
- -

Further assume that the definition of WorkerBee is as used earlier in this chapter. In this case, the dennis object has these properties:

- -
dennis.name == "Doe, Dennis"
-dennis.dept == "engineering"
-dennis.projects == ["collabra"]
-dennis.machine == "hugo"
-dennis.hobby == "scuba"
-
- -

So dennis does get the hobby property from the Hobbyist constructor. However, assume you then add a property to the Hobbyist constructor's prototype:

- -
Hobbyist.prototype.equipment = ["mask", "fins", "regulator", "bcd"]
-
- -

The dennis object does not inherit this new property.

- -
{{PreviousNext("Web/JavaScript/Guide/Working_with_Objects", "Web/JavaScript/Guide/Iterators_and_Generators")}}
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 ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Functions", "Web/JavaScript/Guide/Numbers_and_dates")}}
-

Este capítulo descreve expressões e operadores JavaScript, incluindo atribuição, comparação, aritmética, bit a bit, lógico, string, e operadores especiais.

- -

Expressões

- -

Uma expressão é qualquer unidade de código válida que resolve um valor.

- -

Conceitualmente, há dois tipos de expressões: aqueles que atribui um valor para uma variável, e aqueles que simplesmente tem um valor. Por exemplo, a expressão x = 7 é uma expressão que atribui a x o valor sete. Esta expressão avalia-se a sete. Tais expressões usam operadores de atribuição. Por outro lado, a expressão de 3 + 4 simplesmente avalia a sete; ele não realiza uma atribuição. Os operadores usados ​​em tais expressões são referidos simplesmente como operadores.

- -

JavaScript tem os seguintes tipos de expressões:

- - - -

Operadores

- -

JavaScript tem os seguintes tipos de operadores. Esta seção descreve os operadores e contém informações sobre a precedência do operador.

- - - -

JavaScript has both binary and unary operators, and one special ternary operator, the conditional operator. A binary operator requires two operands, one before the operator and one after the operator:

- -
operand1 operator operand2
-
- -

For example, 3+4 or x*y.

- -

A unary operator requires a single operand, either before or after the operator:

- -
operator operand
-
- -

or

- -
operand operator
-
- -

For example, x++ or ++x.

- -

Assignment operators

- -

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.

- -

The other assignment operators are shorthand for standard operations, as shown in the following table.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Table 3.1 Assignment operators
Shorthand operatorMeaning
x += yx = x + y
x -= yx = x - y
x *= yx = x * y
x /= yx = x / y
x %= yx = x % y
x <<= yx = x << y
x >>= yx = x >> y
x >>>= yx = x >>> y
x &= yx = x & y
x ^= yx = x ^ y
x |= yx = x | y
- -

Comparison operators

- -

This seems to me kind of poorly explained, mostly the difference betwen "==" and "==="... 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 === and !==, 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:

- -
var var1 = 3, var2 = 4;
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Table 3.2 Comparison operators
OperatorDescriptionExamples returning true
Equal (==)Returns true if the operands are equal.3 == var1 -

"3" == var1

- 3 == '3'
Not equal (!=)Returns true if the operands are not equal.var1 != 4
- var2 != "3"
Strict equal (===)Returns true if the operands are equal and of the same type.3 === var1
Strict not equal (!==)Returns true if the operands are not equal and/or not of the same type.var1 !== "3"
- 3 !== '3'
Greater than (>)Returns true if the left operand is greater than the right operand.var2 > var1
- "12" > 2
Greater than or equal (>=)Returns true if the left operand is greater than or equal to the right operand.var2 >= var1
- var1 >= 3
Less than (<)Returns true if the left operand is less than the right operand.var1 < var2
- "12" < "2"
Less than or equal (<=)Returns true if the left operand is less than or equal to the right operand.var1 <= var2
- var2 <= 5
- -

Arithmetic operators

- -

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 NaN). For example:

- -
console.log(1 / 2); /* prints 0.5 */
-console.log(1 / 2 == 1.0 / 2.0); /* also this is true */
-
- -

In addition, JavaScript provides the arithmetic operators listed in the following table.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Table 3.3 Arithmetic operators
OperatorDescriptionExample
%
- (Modulus)
Binary operator. Returns the integer remainder of dividing the two operands.12 % 5 returns 2.
++
- (Increment)
Unary operator. Adds one to its operand. If used as a prefix operator (++x), returns the value of its operand after adding one; if used as a postfix operator (x++), returns the value of its operand before adding one.If x is 3, then ++x sets x to 4 and returns 4, whereas x++ returns 3 and, only then, sets x to 4.
--
- (Decrement)
Unary operator. Subtracts one from its operand. The return value is analogous to that for the increment operator.If x is 3, then --x sets x to 2 and returns 2, whereas x-- returns 3 and, only then, sets x to 2.
-
- (Unary negation)
Unary operator. Returns the negation of its operand.If x is 3, then -x returns -3.
- -

Bitwise operators

- -

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.

- -

The following table summarizes JavaScript's bitwise operators.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Table 3.4 Bitwise operators
OperatorUsageDescription
Bitwise ANDa & bReturns a one in each bit position for which the corresponding bits of both operands are ones.
Bitwise ORa | bReturns a one in each bit position for which the corresponding bits of either or both operands are ones.
Bitwise XORa ^ bReturns a one in each bit position for which the corresponding bits of either but not both operands are ones.
Bitwise NOT~ aInverts the bits of its operand.
Left shifta << bShifts a in binary representation b bits to the left, shifting in zeros from the right.
Sign-propagating right shifta >> bShifts a in binary representation b bits to the right, discarding bits shifted off.
Zero-fill right shifta >>> bShifts a in binary representation b bits to the right, discarding bits shifted off, and shifting in zeros from the left.
- -

Bitwise logical operators

- -

Conceptually, the bitwise logical operators work as follows:

- - - -

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:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Table 3.5 Bitwise operator examples
ExpressionResultBinary Description
15 & 991111 & 1001 = 1001
15 | 9151111 | 1001 = 1111
15 ^ 961111 ^ 1001 = 0110
~150~1111 = 0000
~96~1001 = 0110
- -

 

- -

Bitwise shift operators

- -

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.

- -

Shift operators convert their operands to thirty-two-bit integers and return a result of the same type as the left operand.

- -

The shift operators are listed in the following table.

- - - - - - - - - - - - - - - - - - - - - - - - - - - -
Table 3.6 Bitwise shift operators
OperatorDescriptionExample
<<
- (Left shift)
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.9<<2 yields 36, because 1001 shifted 2 bits to the left becomes 100100, which is 36.
>>
- (Sign-propagating right shift)
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.9>>2 yields 2, because 1001 shifted 2 bits to the right becomes 10, which is 2. Likewise, -9>>2 yields -3, because the sign is preserved.
>>>
- (Zero-fill right shift)
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.19>>>2 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.
- -

Logical operators

- -

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.

- - - - - - - - - - - - - - - - - - - - - - - - - - - -
Table 3.6 Logical operators
OperatorUsageDescription
&&expr1 && expr2(Logical AND) Returns expr1 if it can be converted to false; otherwise, returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, returns false.
||expr1 || expr2(Logical OR) Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true; if both are false, returns false.
!!expr(Logical NOT) Returns false if its single operand can be converted to true; otherwise, returns true.
- -

Examples of expressions that can be converted to false are those that evaluate to null, 0, the empty string (""), or undefined.

- -

The following code shows examples of the && (logical AND) operator.

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

The following code shows examples of the || (logical OR) operator.

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

The following code shows examples of the ! (logical NOT) operator.

- -
var n1 = !true;  // !t returns false
-var n2 = !false; // !f returns true
-var n3 = !"Cat"; // !t returns false
-
- -

Short-circuit evaluation

- -

As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:

- - - -

The rules of logic guarantee that these evaluations are always correct. Note that the anything part of the above expressions is not evaluated, so any side effects of doing so do not take effect.

- -

String operators

- -

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, "my " + "string" returns the string "my string".

- -

The shorthand assignment operator += can also be used to concatenate strings. For example, if the variable mystring has the value "alpha", then the expression mystring += "bet" evaluates to "alphabet" and assigns this value to mystring.

- -

Special operators

- -

JavaScript provides the following special operators:

- - - -

Conditional operator

- -

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:

- -
condition ? val1 : val2
-
- -

If condition is true, the operator has the value of val1. Otherwise it has the value of val2. You can use the conditional operator anywhere you would use a standard operator.

- -

For example,

- -
var status = (age >= 18) ? "adult" : "minor";
-
- -

This statement assigns the value "adult" to the variable status if age is eighteen or more. Otherwise, it assigns the value "minor" to status.

- -

Comma operator

- -

The comma operator (,) simply evaluates both of its operands and returns the value of the second operand. This operator is primarily used inside a for loop, to allow multiple variables to be updated each time through the loop.

- -

For example, if a 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:

- -
for (var i = 0, j = 9; i <= 9; i++, j--)
-  document.writeln("a[" + i + "][" + j + "]= " + a[i][j]);
-
- -

delete

- -

The delete operator deletes an object, an object's property, or an element at a specified index in an array. The syntax is:

- -
delete objectName;
-delete objectName.property;
-delete objectName[index];
-delete property; // legal only within a with statement
-
- -

where objectName is the name of an object, property is an existing property, and index is an integer representing the location of an element in an array.

- -

The fourth form is legal only within a with statement, to delete a property from an object.

- -

You can use the delete operator to delete variables declared implicitly but not those declared with the var statement.

- -

If the delete operator succeeds, it sets the property or element to undefined. The delete operator returns true if the operation is possible; it returns false if the operation is not possible.

- -
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)
-
- -
Deleting array elements
- -

When you delete an array element, the array length is not affected. For example, if you delete a[3], a[4] is still a[4] and a[3] is undefined.

- -

When the delete operator removes an array element, that element is no longer in the array. In the following example, trees[3] is removed with delete. However, trees[3] is still addressable and returns undefined.

- -
var trees = new Array("redwood", "bay", "cedar", "oak", "maple");
-delete trees[3];
-if (3 in trees) {
-  // this does not get executed
-}
-
- -

If you want an array element to exist but have an undefined value, use the undefined keyword instead of the delete operator. In the following example, trees[3] is assigned the value undefined, but the array element still exists:

- -
var trees = new Array("redwood", "bay", "cedar", "oak", "maple");
-trees[3] = undefined;
-if (3 in trees) {
-  // this gets executed
-}
-
- -

in

- -

The in operator returns true if the specified property is in the specified object. The syntax is:

- -
propNameOrNumber in objectName
-
- -

where propNameOrNumber is a string or numeric expression representing a property name or array index, and objectName is the name of an object.

- -

The following examples show some uses of the in operator.

- -
// 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
-
- -

instanceof

- -

The instanceof operator returns true if the specified object is of the specified object type. The syntax is:

- -
objectName instanceof objectType
-
- -

where objectName is the name of the object to compare to objectType, and objectType is an object type, such as Date or Array.

- -

Use instanceof 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.

- -

For example, the following code uses instanceof to determine whether theDay is a Date object. Because theDay is a Date object, the statements in the if statement execute.

- -
var theDay = new Date(1995, 12, 17);
-if (theDay instanceof Date) {
-  // statements to execute
-}
-
- -

new

- -

You can use the new operator to create an instance of a user-defined object type or of one of the predefined object types Array, Boolean, Date, Function, Image, Number, Object, Option, RegExp, or String. On the server, you can also use it with DbPool, Lock, File, or SendMail. Use new as follows:

- -
var objectName = new objectType([param1, param2, ..., paramN]);
-
- -

You can also create objects using object initializers, as described in {{ web.link("Working_with_objects#Using_object_initializers", "using object initializers") }}.

- -

See the new operator page in the Core JavaScript Reference for more information.

- -

this

- -

Use the this keyword to refer to the current object. In general, this refers to the calling object in a method. Use this as follows:

- -
this["propertyName"]
-
- -
this.propertyName
-
- -

Example 1.
- Suppose a function called validate validates an object's value property, given the object and the high and low values:

- -
function validate(obj, lowval, hival){
-  if ((obj.value < lowval) || (obj.value > hival))
-    alert("Invalid Value!");
-}
-
- -

You could call validate in each form element's onChange event handler, using this to pass it the form element, as in the following example:

- -
<B>Enter a number between 18 and 99:</B>
-<INPUT TYPE="text" NAME="age" SIZE=3
-   onChange="validate(this, 18, 99);">
-
- -

Example 2.
- When combined with the form property, this can refer to the current object's parent form. In the following example, the form myForm contains a Text object and a button. When the user clicks the button, the value of the Text object is set to the form's name. The button's onClick event handler uses this.form to refer to the parent form, myForm.

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

typeof

- -

The typeof operator is used in either of the following ways:

- -
    -
  1. -
    typeof operand
    -
    -
  2. -
  3. -
    typeof (operand)
    -
    -
  4. -
- -

The typeof operator returns a string indicating the type of the unevaluated operand. operand is the string, variable, keyword, or object for which the type is to be returned. The parentheses are optional.

- -

Suppose you define the following variables:

- -
var myFun = new Function("5 + 2");
-var shape = "round";
-var size = 1;
-var today = new Date();
-
- -

The typeof operator returns the following results for these variables:

- -
typeof myFun;     // returns "function"
-typeof shape;     // returns "string"
-typeof size;      // returns "number"
-typeof today;     // returns "object"
-typeof dontExist; // returns "undefined"
-
- -

For the keywords true and null, the typeof operator returns the following results:

- -
typeof true; // returns "boolean"
-typeof null; // returns "object"
-
- -

For a number or string, the typeof operator returns the following results:

- -
typeof 62;            // returns "number"
-typeof 'Hello world'; // returns "string"
-
- -

For property values, the typeof operator returns the type of value the property contains:

- -
typeof document.lastModified; // returns "string"
-typeof window.length;         // returns "number"
-typeof Math.LN2;              // returns "number"
-
- -

For methods and functions, the typeof operator returns results as follows:

- -
typeof blur;        // returns "function"
-typeof eval;        // returns "function"
-typeof parseInt;    // returns "function"
-typeof shape.split; // returns "function"
-
- -

For predefined objects, the typeof operator returns results as follows:

- -
typeof Date;     // returns "function"
-typeof Function; // returns "function"
-typeof Math;     // returns "object"
-typeof Option;   // returns "function"
-typeof String;   // returns "function"
-
- -

void

- -

The void operator is used in either of the following ways:

- -
    -
  1. -
    void (expression)
    -
    -
  2. -
  3. -
    void expression
    -
    -
  4. -
- -

The void operator specifies an expression to be evaluated without returning a value. expression is a JavaScript expression to evaluate. The parentheses surrounding the expression are optional, but it is good style to use them.

- -

You can use the void operator to specify an expression as a hypertext link. The expression is evaluated but is not loaded in place of the current document.

- -

The following code creates a hypertext link that does nothing when the user clicks it. When the user clicks the link, void(0) evaluates to undefined, which has no effect in JavaScript.

- -
<A HREF="javascript:void(0)">Click here to do nothing</A>
-
- -

The following code creates a hypertext link that submits a form when the user clicks it.

- -
<A HREF="javascript:void(document.form.submit())">
-Click here to submit</A>
- -

Operator precedence

- -

The precedence of operators determines the order they are applied when evaluating an expression. You can override operator precedence by using parentheses.

- -

The following table describes the precedence of operators, from highest to lowest.

- -

In accordance with relevant discussion, this table was reversed to list operators in decreasing order of priority.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Table 3.7 Operator precedence
Operator typeIndividual operators
member. []
call / create instance() new
negation/increment! ~ - + ++ -- typeof void delete
multiply/divide* / %
addition/subtraction+ -
bitwise shift<< >> >>>
relational< <= > >= in instanceof
equality== != === !==
bitwise-and&
bitwise-xor^
bitwise-or|
logical-and&&
logical-or||
conditional?:
assignment= += -= *= /= %= <<= >>= >>>= &= ^= |=
comma,
- -

A more detailed version of this table, complete with links to additional details about each operator, may be found in JavaScript Reference.

diff --git "a/files/pt-pt/web/javascript/guia/gram\303\241tica_e_tipos/index.html" "b/files/pt-pt/web/javascript/guia/gram\303\241tica_e_tipos/index.html" deleted file mode 100644 index 109bd99fe4..0000000000 --- "a/files/pt-pt/web/javascript/guia/gram\303\241tica_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 ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Introduction", "Web/JavaScript/Guide/Control_flow_and_error_handling")}}
- -

Este capítulo discute a gramática básica do JavaScript, declarações de variáveis, tipos de dados e literais.

- -

Básicos

- -

JavaScript borrows most of its syntax from Java, but is also influenced by Awk, Perl and Python.

- -

JavaScript is case-sensitive and uses the Unicode character set.

- -

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 (ASI) 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 lexical grammar.

- -

Comentários

- -

The syntax of comments is the same as in C++ and in many other languages:

- -
// a one line comment
-
-/* this is a longer,
-   multi-line comment
- */
-
-/* You can't, however, /* nest comments */ SyntaxError */
- -

Declarações

- -

There are three kinds of declarations in JavaScript.

- -
-
{{jsxref("Statements/var", "var")}}
-
Declares a variable, optionally initializing it to a value.
-
{{experimental_inline}} {{jsxref("Statements/let", "let")}}
-
Declares a block scope local variable, optionally initializing it to a value.
-
{{experimental_inline}} {{jsxref("Statements/const", "const")}}
-
Declares a read-only named constant.
-
- -

Variáveis

- -

You use variables as symbolic names for values in your application. The names of variables, called {{Glossary("Identifier", "identifiers")}}, conform to certain rules.

- -

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).

- -

You can use ISO 8859-1 or Unicode letters such as å and ü in identifiers. You can also use the Unicode escape sequences as characters in identifiers.

- -

Some examples of legal names are Number_hits, temp99, and _name.

- -

Declararação de variáveis

- -

You can declare a variable in three ways:

- - - -

Avaliação de variáveis

- -

A variable declared using the var statement with no initial value specified has the value {{jsxref("undefined")}}.

- -

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:

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

You can use undefined to determine whether a variable has a value. In the following code, the variable input is not assigned a value, and the if statement evaluates to true.

- -
var input;
-if(input === undefined){
-  doThis();
-} else {
-  doThat();
-}
-
- -

The undefined value behaves as false when used in a boolean context. For example, the following code executes the function myFunction because the myArray element is undefined:

- -
var myArray = [];
-if (!myArray[0]) myFunction();
-
- -

The undefined value converts to NaN when used in numeric context.

- -
var a;
-a + 2;  // Evaluates to NaN
- -

When you evaluate a {{jsxref("null")}} variable, the null value behaves as 0 in numeric contexts and as false in boolean contexts. For example:

- -
var n = null;
-console.log(n * 32); // Will log 0 to the console
-
- -

Variable scope

- -

When you declare a variable outside of any function, it is called a global 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 local variable, because it is available only within that function.

- -

JavaScript before ECMAScript 2015 does not have block statement scope; rather, a variable declared within a block is local to the function (or global scope) that the block resides within. For example the following code will log 5, because the scope of x is the function (or global context) within which x is declared, not the block, which in this case is an if statement.

- -
if (true) {
-  var x = 5;
-}
-console.log(x);  // 5
-
- -

This behavior changes, when using the let declaration introduced in ECMAScript 2015.

- -
if (true) {
-  let y = 5;
-}
-console.log(y);  // ReferenceError: y is not defined
-
- -

Variable hoisting

- -

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 hoisting; 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 undefined. So even if you declare and initialize after you use or refer to this variable, it will still return undefined.

- -
/**
- * 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";
-})();
-
- -

The above examples will be interpreted the same as:

- -
/**
- * 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";
-})();
-
- -

Because of hoisting, all var 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.

- -

In ECMAScript 2015, let (const) will not hoist the variable to the top of the block. However, referencing the variable in the block before the variable declaration results in a ReferenceError. The variable is in a "temporal dead zone" from the start of the block until the declaration is processed.

- -
console.log(x); // ReferenceError
-let x = 3;
- -

Variáveis gGlobais

- -

Global variables are in fact properties of the global object. In web pages the global object is {{domxref("window")}}, so you can set and access global variables using the window.variable syntax.

- -

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 phoneNumber is declared in a document, you can refer to this variable from an iframe as parent.phoneNumber.

- -

Constantes

- -

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.

- -
const PI = 3.14;
-
- -

A constant cannot change value through assignment or be re-declared while the script is running. It has to be initialized to a value.

- -

The scope rules for constants are the same as those for let block scope variables. If the const keyword is omitted, the identifier is assumed to represent a variable.

- -

You cannot declare a constant with the same name as a function or variable in the same scope. For example:

- -
// THIS WILL CAUSE AN ERROR
-function f() {};
-const f = 5;
-
-// THIS WILL CAUSE AN ERROR ALSO
-function f() {
-  const g = 5;
-  var g;
-
-  //statements
-}
-
- -

However, object attributes are not protected, so the following statement is executed without problems.

- -
const MY_OBJECT = {"key": "value"};
-MY_OBJECT.key = "otherValue";
- -

Estruturas e tipode dados

- -

tipos de dados

- -

The latest ECMAScript standard defines seven data types:

- - - -

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.

- -

Conversão de tipo de dados

- -

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:

- -
var answer = 42;
-
- -

And later, you could assign the same variable a string value, for example:

- -
answer = "Thanks for all the fish...";
-
- -

Because JavaScript is dynamically typed, this assignment does not cause an error message.

- -

In expressions involving numeric and string values with the + operator, JavaScript converts numeric values to strings. For example, consider the following statements:

- -
x = "The answer is " + 42 // "The answer is 42"
-y = 42 + " is the answer" // "42 is the answer"
-
- -

In statements involving other operators, JavaScript does not convert numeric values to strings. For example:

- -
"37" - 7 // 30
-"37" + 7 // "377"
-
- -

Conversão de strings para números

- -

In the case that a value representing a number is in memory as a string, there are methods for conversion.

- - - -

parseInt will only return whole numbers, so its use is diminished for decimals. Additionally, a best practice for parseInt is to always include the radix parameter. The radix parameter is used to specify which numerical system is to be used.

- -

An alternative method of retrieving a number from a string is with the + (unary plus) operator:

- -
"1.1" + "1.1" = "1.11.1"
-(+"1.1") + (+"1.1") = 2.2
-// Note: the parentheses are added for clarity, not required.
- -

Literais

- -

You use literals to represent values in JavaScript. These are fixed values, not variables, that you literally provide in your script. This section describes the following types of literals:

- - - -

Literais de tabela

- -

An array literal is a list of zero or more expressions, each of which represents an array element, enclosed in square brackets ([]). 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.

- -

The following example creates the coffees array with three elements and a length of three:

- -
var coffees = ["French Roast", "Colombian", "Kona"];
-
- -
-

Note : An array literal is a type of object initializer. See Using Object Initializers.

-
- -

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.

- -

Array literals are also Array objects. See {{jsxref("Array")}} and Indexed collections for details on Array objects.

- -

Extra commas in array literals

- -

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 undefined for the unspecified elements. The following example creates the fish array:

- -
var fish = ["Lion", , "Angel"];
-
- -

This array has two elements with values and one empty element (fish[0] is "Lion", fish[1] is undefined, and fish[2] is "Angel").

- -

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 myList[3]. All other commas in the list indicate a new element.

- -
-

Nota : Trailing commas can create errors in older browser versions and it is a best practice to remove them.

-
- -
var myList = ['home', , 'school', ];
-
- -

In the following example, the length of the array is four, and myList[0] and myList[2] are missing.

- -
var myList = [ , 'home', , 'school'];
-
- -

In the following example, the length of the array is four, and myList[1] and myList[3] are missing. Only the last comma is ignored.

- -
var myList = ['home', , 'school', , ];
-
- -

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 undefined will increase your code's clarity and maintainability.

- -

Lietrais boolianas

- -

The Boolean type has two literal values: true and false.

- -

Do not confuse the primitive Boolean values true and false 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.

- -

Íntegros

- -

Integers can be expressed in decimal (base 10), hexadecimal (base 16), octal (base 8) and binary (base 2).

- - - -

Some examples of integer literals are:

- -
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)
-
- -

For more information, see Numeric literals in the Lexical grammar reference.

- -

Literais de ponto flutuante

- -

A floating-point literal can have the following parts:

- - - -

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").

- -

More succinctly, the syntax is:

- -
[(+|-)][digits][.digits][(E|e)[(+|-)]digits]
-
- -

For example:

- -
3.1415926
--.123456789
--3.1E+12
-.1e-23
-
- -

Literais de objeto

- -

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.

- -

The following is an example of an object literal. The first element of the car object defines a property, myCar, and assigns to it a new string, "Saturn"; the second element, the getCar property, is immediately assigned the result of invoking the function (carTypes("Honda")); the third element, the special property, uses an existing variable (sales).

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

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.

- -
var car = { manyCars: {a: "Saab", "b": "Jeep"}, 7: "Mazda" };
-
-console.log(car.manyCars.b); // Jeep
-console.log(car[7]); // Mazda
-
- -

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 (.) property, but can be accessed and set with the array-like notation("[]").

- -
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!
- -

In ES2015, object literals are extended to support setting the prototype at construction, shorthand for foo: foo 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.

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

Por favor, note:

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

RegExp literals

- -

A regex literal is a pattern enclosed between slashes. The following is an example of an regex literal.

- -
var re = /ab+c/;
- -

Lietrais de string

- -

A string literal is zero or more characters enclosed in double (") or single (') 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:

- -
"foo"
-'bar'
-"1234"
-"one line \n another line"
-"John's cat"
-
- -

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 String.length property with a string literal:

- -
console.log("John's cat".length)
-// Will print the number of symbols in the string including whitespace.
-// In this case, 10.
-
- -

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.

- -
// 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);
- -

You should use string literals unless you specifically need to use a String object. See {{jsxref("String")}} for details on String objects.

- -

Using special characters in strings

- -

In addition to ordinary characters, you can also include special characters in strings, as shown in the following example.

- -
"one line \n another line"
-
- -

The following table lists the special characters that you can use in JavaScript strings.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Table: JavaScript special characters
CáraterSignificado
\0Null Byte
\bBackspace
\fForm feed
\nNew line
\rCarriage return
\tTab
\vVertical tab
\'Apostrophe or single quote
\"Double quote
\\Backslash character
\XXXThe character with the Latin-1 encoding specified by up to three octal digits XXX between 0 and 377. For example, \251 is the octal sequence for the copyright symbol.
\xXXThe character with the Latin-1 encoding specified by the two hexadecimal digits XX between 00 and FF. For example, \xA9 is the hexadecimal sequence for the copyright symbol.
\uXXXXThe Unicode character specified by the four hexadecimal digits XXXX. For example, \u00A9 is the Unicode sequence for the copyright symbol. See Unicode escape sequences.
\u{XXXXX}Unicode code point escapes. For example, \u{2F804} is the same as the simple Unicode escapes \uD87E\uDC04.
- -

Escaping characters

- -

For characters not listed in the table, a preceding backslash is ignored, but this usage is deprecated and should be avoided.

- -

You can insert a quotation mark inside a string by preceding it with a backslash. This is known as escaping the quotation mark. For example:

- -
var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service.";
-console.log(quote);
-
- -

The result of this would be:

- -
He read "The Cremation of Sam McGee" by R.W. Service.
-
- -

To include a literal backslash inside a string, you must escape the backslash character. For example, to assign the file path c:\temp to a string, use the following:

- -
var home = "c:\\temp";
-
- -

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.

- -
var str = "this string \
-is broken \
-across multiple\
-lines."
-console.log(str);   // this string is broken across multiplelines.
-
- -

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:

- -
var poem =
-"Roses are red,\n\
-Violets are blue.\n\
-Sugar is sweet,\n\
-and so is foo."
-
- -

Mais informação

- -

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:

- - - -

In the next chapter, we will have a look at control flow constructs and error handling.

- -

{{PreviousNext("Web/JavaScript/Guide/Introduction", "Web/JavaScript/Guide/Control_flow_and_error_handling")}}

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 ---- -
{{jsSidebar("JavaScript Guide")}}
- -

The JavaScript Guide shows you how to use JavaScript and gives an overview of the language. If you want to get started with JavaScript or programming in general, consult the articles in the learning area. If you need exhaustive information about a language feature, have a look at the JavaScript reference.

- -

Capítulos

- -

This Guide is divided into several chapters:

- - - - - - - - - -

{{Next("Web/JavaScript/Guide/Introduction")}}

diff --git "a/files/pt-pt/web/javascript/guia/introdu\303\247\303\243o/index.html" "b/files/pt-pt/web/javascript/guia/introdu\303\247\303\243o/index.html" deleted file mode 100644 index f77bb74379..0000000000 --- "a/files/pt-pt/web/javascript/guia/introdu\303\247\303\243o/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 ---- -
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide", "Web/JavaScript/Guide/Grammar_and_types")}}
- -

Este capítulo apresenta a linguagem JavaScript e discuste alguns dos seus conceitos fundamentais.

- -

O que você já deveria saber

- -

Este guia assume que você possuí os seguintes conhecimentos:

- - - -

Onde encontrar informação sobre JavaScript?

- -

A documentação de JavaScript no MDN incluí o seguinte:

- - - -

Se for iniciante em JavaScript, comece lendo alguns dos artigos na área de aprendizagem e o  Guia de JavaScript. Assim que compreender os fundamentos da linguagem, pode consultar a Referência de JavaScript para obter mais detalhes sobre objetos individuais e declarações.

- -

O que é JavaScript?

- -

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.

- -

O JavaScript contém uma biblioteca padrão de objetos, tais como ArrayDateMath, 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:

- - - -

JavaScript e Java

- -

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.

- -

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.

- -

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.

- -

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.

- -

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.

- - - - - - - - - - - - - - - - - - - - - - - -
JavaScript comparado com Java
JavaScriptJava
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.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.
Variable data types are not declared (dynamic typing).Variable data types must be declared (static typing).
Cannot automatically write to hard disk.Can automatically write to hard disk.
- -

For more information on the differences between JavaScript and Java, see the chapter Details of the object model.

- -

JavaScript e a especificação ECMAScript

- -

JavaScript is standardized at Ecma International — 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 New in JavaScript to learn more about different versions of JavaScript and ECMAScript specification editions.

- -

The ECMA-262 standard is also approved by the ISO (International Organization for Standardization) as ISO-16262. You can also find the specification on the Ecma International website. The ECMAScript specification does not describe the Document Object Model (DOM), which is standardized by the World Wide Web Consortium (W3C) and/or WHATWG (Web Hypertext Application Technology Working Group). 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 JavaScript technologies overview.

- -

Documentação JavaScript versus especificação  ECMAScript

- -

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).

- -

The ECMAScript document is not intended to help script programmers; use the JavaScript documentation for information on writing scripts.

- -

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.

- -

The JavaScript documentation describes aspects of the language that are appropriate for a JavaScript programmer.

- -

Começar com JavaScript

- -

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.

- -

There are two tools built into Firefox that are useful for experimenting with JavaScript: the Web Console and Scratchpad.

- -

A Consola da Web

- -

A Consola da Web shows you information about the currently loaded Web page, and also includes a command line that you can use to execute JavaScript expressions in the current page.

- -

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:

- -

- -

Scratchpad

- -

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 Scratchpad is a better tool.

- -

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.

- -

- -

Olá mundo

- -

To get started with writing JavaScript, open the Scratchpad and write your first "Hello world" JavaScript code:

- -
function greetMe(yourName) {
-  alert("Hello " + yourName);
-}
-
-greetMe("World");
-
- -

Select the code in the pad and hit Ctrl+R to watch it unfold in your browser!

- -

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.

- -

{{PreviousNext("Web/JavaScript/Guide", "Web/JavaScript/Guide/Grammar_and_types")}}

diff --git "a/files/pt-pt/web/javascript/guia/introdu\303\247\303\243o_ao_javascript/index.html" "b/files/pt-pt/web/javascript/guia/introdu\303\247\303\243o_ao_javascript/index.html" deleted file mode 100644 index 549ecbe331..0000000000 --- "a/files/pt-pt/web/javascript/guia/introdu\303\247\303\243o_ao_javascript/index.html" +++ /dev/null @@ -1,47 +0,0 @@ ---- -title: Introdução ao JavaScript -slug: Web/JavaScript/Guia/Introdução_ao_JavaScript ---- -

Este capítulo introduz o JavaScript e discute alguns de seus conceitos fundamentais.

-

O que é o JavaScript?

-

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.

-

O núcleo do JavaScript contém um  núcleo de objetos, como Array, Date, e Math, 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:

- -

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.

-

O Netscape inventou o JavaScript e o JavaScript foi inicialmente usado em navegadores Netscape.

-

JavaScript e Java

-

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.

-

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.

-

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.

-

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.

-

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.

- -
Tabela 1.1 JavaScript em comparação ao Java
JavaScript Java
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. 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.
Tipos de dados variáveis não são declarados (tipagem dinâmica). Tipos de dados variáveis precisam ser declarados (tipagem estática).
Não pode escrever automaticamente no disco rígido. Não pode escrever automaticamente no disco rígido.
-

Para mais informações sobre as diferenças entre o JavaScript e o Java, veja o capítulo Details of the Object Model.

JavaScript e a especificação ECMAScript

-

O Netscape inventou o JavaScript e o JavaScript foi primeiramente usado nos navegadores Netscape. Entretanto, a Netscape está trabalhando com a Ecma International — 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.

-

O padrão ECMA-262 é também aprovado pela ISO (International Organization for Standardization, em português: Organização Internacional para Padronização) como ISO-16262. Você pode encontrar uma versão PDF do ECMA-262 (en) no site da Mozilla. Você pode também encontrar a especificação em the Ecma International website (en). A especificação do ECMAScript não descreve o Document Object Model (DOM), o qual é padronizado pelo World Wide Web Consortium (W3C). O DOM define a maneira com a qual os objetos do documento HTML são expostos ao seu script.

-

Relação entre as versões do JavaScript e as edições do ECMAScript

-

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.

- -
Tabela 1.2 Versões do JavaScript e edições do ECMAScript
Versão do JavaScript Relação com a edição do ECMAScript
JavaScript 1.1 O ECMA-262, Edição 1 é baseado no JavaScript 1.1.
JavaScript 1.2 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:
  • O Netscape desenvolveu características adicionais no JavaScript 1.2 que não foram consideradas no ECMA-262.
  • 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 Date, eram dependentes de plataforma e usavam um comportamento específico da plataforma.

JavaScript 1.3

O JavaScript 1.3 é totalmente compatível com o ECMA-262, Edição 1.

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.

JavaScript 1.4

O JavaScript 1.4 é totalmente comatível com o ECMA-262, Edição 1.

A terceira versão da especificação ECMAScript não estava finalizada quando o JavaScript 1.4 foi lançado.

JavaScript 1.5 O JavaScript 1.5 é totalmente compatível com o ECMA-262, Edição 3.
-
Nota: 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.
-

A Referência de JavaScript (en) indica quais características da linguagem estão em conformidade com o ECMAScript.

-

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.

Documentação do JavaScript versus a especificação do ECMAScript

-

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.

-

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.

Terminologia do JavaScript e do ECMAScript

-

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.

-

A documentação do JavaScript descreve aspectos da linguagem que são apropriados para um programador JavaScript. Por exemplo:

- -
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_概要"
-});
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 ---- -

JavaScript é uma linguagem de scripts multiplataforma, baseada em objetos. Este guia explica tudo que é necessário saber sobre como utilizar o JavaScript.

- -

Novas caraterísticas em versões do JavaScript

- -
/* 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>;
- -

O que já é necessário saber

- -

Este guia assume que já possui os seguintes conhecimentos como base:

- - - -

Alguma experiência de programação com uma linguagem como C ou Visual Basic é útil, mas não necessária.

- -

Versões do JavaScript

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Tabela 1 Versões do JavaScript e do Navigator
versão JavaScriptversão Navigator
JavaScript 1.0Navigator 2.0
JavaScript 1.1Navigator 3.0
JavaScript 1.2Navigator 4.0-4.05
JavaScript 1.3Navigator 4.06-4.7x
JavaScript 1.4 
JavaScript 1.5Navigator 6.0
- Mozilla (navegador open source)
JavaScript 1.6Firefox 1.5, outros produtos baseados no Mozilla 1.8
JavaScript 1.7Firefox 2, outros produtos baseados no Mozilla 1.8.1
JavaScript 1.8Firefox 3, outros produtos baseados no Gecko 1.9
- -

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.

- - - - - - - - - - - - - - - - - - - -
Tabela 2 Abreviações das versões do Netscape Enterprise Server
Abreviaçãoversão Enterprise Server
NES 2.0Netscape Enterprise Server 2.0
NES 3.0Netscape Enterprise Server 3.0
- -

Onde encontrar informações sobre JavaScript

- -

A documentação do JavaScript inclui os seguintes livros:

- - - -

Se você é novo no JavaScript, comece com o Guia de JavaScript. Uma vez que você tenha uma boa compreensão dos fundamentos, você pode usar a Referência JavaScript para obter mais detalhes sobre objetos e declarações.

- -

Dicas para aprender JavaScript

- -

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.

- -

Um interpretador interativo

- -

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".

- -

Image:ErrorConsole.png

- -

Firebug

- -

Uma linha de comando interativa mais avançada está disponível com o uso do Firebug, 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.

- -

Image:Firebug.png

- -

Um dos mais úteis benefícios proporcionados pelo Firebug é console.log(), 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 console.log() fornece uma alternativa útil, tornando mais fácil ver o que seu programa está fazendo.

- -

Muitos dos exemplos neste guia usam alert() para exibir mensagens conforme são executados. Tendo o Firebug instalado, pode ser usando console.log() ao invés de alert() ao rodar estes exemplos.

- -

Convenções de documento

- -

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.

- -

Este guia usa localizador padrão de recursos (uniform resource locators (URL)) da seguinte forma:

- -

http://server.domain/path/file.html

- -

Nestas URL, server representa o nome do servidor no qual a aplicação é rodada, tal como research1 ou www; domain representa seu domínio de internet, como netscape.com ou uiuc.edu; path representa a estrutura do diretório no servidor; e file.html representa o nome de um arquivo individual. No geral, itens em itálico em são placeholders e itens em fonte monoespaçada normal são literais. Se o servidor possuir Secure Sockets Layer (SSL) habilitado, pode ser usado https ao invés de http na URL.

- -

Este guia utiliza as seguintes convenções de fontes:

- - - -
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_教學/關於"
-})
-
diff --git "a/files/pt-pt/web/javascript/guia/valores,_vari\303\241veis_e_literais/index.html" "b/files/pt-pt/web/javascript/guia/valores,_vari\303\241veis_e_literais/index.html" deleted file mode 100644 index c2cbc7f3db..0000000000 --- "a/files/pt-pt/web/javascript/guia/valores,_vari\303\241veis_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' ---- -

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.

- -

Valores

- -

O JavaScript reconhece os seguintes tipos de valores:

- - - -

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 Date (en) e seus métodos para lidar com datas.

- -

Objetos (en) e funções (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.

- -

Conversão de tipos de dados

- -

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:

- -
var resposta = 42;
-
- -

E depois, pode-se atribuir para a mesma variável um valor de string, por exemplo:

- -
resposta = "Obrigado pelos peixes...";
-
- -

Como o JavaScript possui tipagem dinâmica, esta atribuição não gera uma mensagem de erro.

- -

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:

- -
x = "A resposta é " + 42 // retorna "A resposta é 42"
-y = 42 + " é a resposta" // retorna "42 é a resposta"
-
- -

Em declarações envolvendo outros operadores, o JavaScript não converte valores numérico para strings. Por exemplo:

- -
"37" - 7 // retorna 30
-"37" + 7 // retorna "377"
- -

Variáveis

- -

Variáveis são usadas como nomes simbólicos para valores em sua aplicação. Os nomes das variáveis, chamadas identificadores, de acordo com certas regras.

- -

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).

- -

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 Sequências de escape em Unicode \uXXXX como caracteres nos identificadores.

- -

Alguns exemplos de nomes possíveis são: Number_hits, temp99 e _name.

- -

Declaração de variáveis

- -

Você pode declarar uma variável de duas maneiras:

- - - -

Avaliação de variáveis

- -

Uma variável declarada usando-se a declaração var sem possuir um valor inicial especificado possui o valor undefined.

- -

Uma tentativa de acesso a uma variável não declarada resultará no lançamento de uma exceção ReferenceError:

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

Você pode usar undefined para determinar quando uma variável possui um valor. No código a seguir, a variável input não possui um valor atribuido e a declaração if é avaliada como true.

- -
var input;
-if(input === undefined){
-  doThis();
-} else {
-  doThat();
-}
-
- -

O valor undefined comporta-se como false quando usado em um contexto booleano. Por exemplo, o código a seguir executa a função myFunction porque o elemento myArray não está definido:

- -
var myArray = new Array();
-if (!myArray[0]) myFunction();
-
- -

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

- -
var n = null;
-print(n * 32); // imprime 0
-
- -

Escopo de variáveis

- -

Quando uma variável é declarada de fora de qualquer função, ele é chamada de variável global, 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 local, pois ela está disponível somente dentro dessa função.

- -

O JavaScript não possui um escopo de declaração de blocos (en); ao contrário, será local para o código interno ao bloco. Por exemplo, o código a seguir imprimirá 0 ao invés de lançar a exceção ReferenceError se condition é false:

- -
if (condition) {
-  var x = 5;
-}
-print(x ? x : 0);
-
- -

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 hoisting; 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 undefined.

- -
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"
-})();
-
- -

Variáveis globais

- -

necessário links para as páginas discutindo cadeias no âmbito do objeto global Variáveis globais são, na verdade, propriedade de um objeto global. Em páginas web o objeto global é window, então você pode configurar e acessar variáveis globais usando a sintaxe window.variable.

- -

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 phoneNumber é declarada em um documento FRAMESET, você pode referir-se a esta variável a partir de um frame herdeiro como parent.phoneNumber.

- -

Veja também

- -

Sharp variables in JavaScript (en)

- -

Constantes

- -

Você pode criar elementos "somente leitura", nomeados constantes com a palavra chave const. 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.

- -
const prefix = '212';
-
- -

Uma constante não pode ter seu valor mudado através de uma atribuição ou ser declarada novamente enquanto o script estiver rodando.

- -

As regras de escopo para constantes são as mesmas que as das variáveis, exceto que a palavra chave const é sempre necessária, mesmo para constantes globais. Se uma palavra chave é omitida, o identificador é assumido como uma variável.

- -

Você não pode declarar uma constante com o mesmo nome de uma função ou variável no mesmo escopo. Por exemplo:

- -
// ISTO CAUSARA UM ERRO
-function f() {};
-const f = 5;
-
-// ISTO TAMBEM CAUSARA UM ERRO
-function f() {
-  const g = 5;
-  var g;
-
-  // declaracoes
-}
-
- -

Literais

- -

Você usa literais para representar valores em JavaScript. Estes valores são fixos, não variáveis, que você fornece literalmente no seu script. Esta seção descreve os seguintes tipos de literais:

- - - -

Ordenação de literais

- -

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.

- -

O exemplo a seguir cria uma ordenação coffees com três elementos e o comprimento de três:

- -
var coffees = ["French Roast", "Colombian", "Kona"];
-
- -

Nota Uma ordenação literal é um tipo de inicializador de objeto. Veja Using Object Initializers (en).

- -

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.

- -

Ordenações literais são também objetos Array.  Veja Array Object (en) para detalhes sobre objetos Array.

- -

Vírgulas extras em literais ordenados

- -

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 fish:

- -
var fish = ["Lion", , "Angel"];
-
- -

Esta ordenação possui dois elementos com valores e um elemento vazio (fish[0] é "Lion", fish[1] é undefined e fish[2] é "Angel").

- -

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á myList[3]. Todas as outras vírgulas da lista indicam um novo elemento.

- -
var myList = ['home', , 'school', ];
-
- -

No exemplo a seguir, o comprimento da ordenação é quatro, e myList[0] e myList[2] estão faltando.

- -
var myList = [ , 'home', , 'school'];
-
- -

No exemplo seguinte, o comprimento da ordenação é quatro, e  myList[1] e myList[3] estão faltando. Somente a última vírgula é ignorada.

- -
var myList = ['home', , 'school', , ];
-
- -

Booleanos literais

- -

O tipo Booleano possui dois valores literais: true e false.

- -

Não confunda-os com os valores Booleanos primitivos true e false com os valores verdadeiro e falso do objeto Booleano. O objeto Booleano é um invólucro ao redor do tipo de dado Booleano. Veja Boolean Object (en) para mais informações.

- -

Inteiros

- -

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.

- -

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.

- -

Alguns exemplo de inteiros literais são:

- -
0, 117 e -345 (decimal, base 10)
-015, 0001 e -077 (octal, base 8)
-0x1123, 0x00111 e -0xF1A7 (hexadecimal, "hex" ou base 16)
-
- -

Pontos flutuantes literais

- -

Um literal de ponto flutuante pode possuir as seguintes partes:

- - - -

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").

- -

Alguns exemplos de pontos flutuantes literais são 3.1415, -3.1E12, .1e12, and 2E-12.

- -

Mais claramente, a sintaxe é:

- -
[digitos][.digitos][(E|e)[(+|-)]digitos]
-
- -

Por exemplo:

- -
3.14
-2345.789
-.3333333333333333333
-
- -

Objetos literais

- -

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.

- -

The following is an example of an object literal. The first element of the car object defines a property, myCar; the second element, the getCar property, invokes a function (CarTypes("Honda")); the third element, the special property, uses an existing variable (Sales).

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

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.

- -
var car = { manyCars: {a: "Saab", "b": "Jeep"}, 7: "Mazda" };
-
-document.write(car.manyCars.b); // Jeep
-document.write(car[7]); // Mazda
-
- -

Please note:

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

Strings literais

- -

A string literal is zero or more characters enclosed in double (") or single (') 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:

- - - -

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 String.length property with a string literal:

- -
"John's cat".length
-
- -

You should use string literals unless you specifically need to use a String object. See String Object for details on String objects.

- -

Usando caracteres especiais em strings

- -

In addition to ordinary characters, you can also include special characters in strings, as shown in the following example.

- -
"one line \n another line"
-
- -

The following table lists the special characters that you can use in JavaScript strings.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Table 2.1 JavaScript special characters
CharacterMeaning
\bBackspace
\fForm feed
\nNew line
\rCarriage return
\tTab
\vVertical tab
\'Apostrophe or single quote
\"Double quote
\\Backslash character (\).
\XXXThe character with the Latin-1 encoding specified by up to three octal digits XXX between 0 and 377. For example, \251 is the octal sequence for the copyright symbol.
\xXXThe character with the Latin-1 encoding specified by the two hexadecimal digits XX between 00 and FF. For example, \xA9 is the hexadecimal sequence for the copyright symbol.
\uXXXXThe Unicode character specified by the four hexadecimal digits XXXX. For example, \u00A9 is the Unicode sequence for the copyright symbol. See Unicode Escape Sequences.
- -

Caracteres de escape

- -

For characters not listed in Table 2.1, a preceding backslash is ignored, but this usage is deprecated and should be avoided.

- -

You can insert a quotation mark inside a string by preceding it with a backslash. This is known as escaping the quotation mark. For example:

- -
var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service.";
-document.write(quote);
-
- -

The result of this would be:

- -
He read "The Cremation of Sam McGee" by R.W. Service.
-
- -

To include a literal backslash inside a string, you must escape the backslash character. For example, to assign the file path c:\temp to a string, use the following:

- -
var home = "c:\\temp";
-
- -

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.

- -
var str = "this string \
-is broken \
-across multiple\
-lines."
- -

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:

- -
var poem =
-"Roses are red,\n\
-Violets are blue.\n\
-I'm schizophrenic,\n\
-And so am I."
-
- -

Unicode

- -

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.

- -

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.

- -

Unicode is not supported in versions of JavaScript prior to 1.3.

- -

Compatibilidade do Unicode com ASCII e ISO

- -

Unicode is fully compatible with the International Standard ISO/IEC 10646-1; 1993, which is a subset of ISO 10646.

- -

Several encoding standards (including UTF-8, UTF-16 and ISO UCS-2) are used to physically represent Unicode as actual bits.

- -

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.

- -

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.

- -

Sequências de escape em Unicode

- -

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.

- -

The following code returns the copyright symbol and the string "Netscape Communications".

- -
var x = "\u00A9 Netscape Communications";
- -

The following table lists frequently used special characters and their Unicode value.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Table 2.2 Unicode values for special characters
CategoryUnicode valueNameFormat name
White space values
-  
-  
-  
\u0009Tab<TAB>
\u000BVertical Tab<VT>
\u000CForm Feed<FF>
\u0020Space<SP>
Line terminator values
-  
\u000ALine Feed<LF>
\u000DCarriage Return<CR>
Additional Unicode escape sequence values
-  
-  
-  
-  
\u0008Backspace<BS>
\u0009Horizontal Tab<HT>
\u0022Double Quote"
\u0027Single Quote'
\u005CBackslash\
- -

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.

- -

Caracteres Unicode em arquivos JavaScript

- -

Earlier versions of Gecko 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 International characters in XUL JavaScript for more information.

- -

Exibindo caracteres com Unicode

- -

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.

- -

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.

- -

For more information on Unicode, see the Unicode Home Page and The Unicode Standard, Version 2.0, published by Addison-Wesley, 1996.

- -
autoPreviousNext("JSGChapters");
diff --git a/files/pt-pt/web/javascript/guide/details_of_the_object_model/index.html b/files/pt-pt/web/javascript/guide/details_of_the_object_model/index.html new file mode 100644 index 0000000000..01de143289 --- /dev/null +++ b/files/pt-pt/web/javascript/guide/details_of_the_object_model/index.html @@ -0,0 +1,735 @@ +--- +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 +--- +
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Working_with_Objects", "Web/JavaScript/Guide/Iterators_and_Generators")}}
+ +
+

The content of this article is under discussion. Please provide feedback and help us to make this page better: {{bug(1201380)}}.

+
+ +

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.

+ +

This chapter assumes that you are already somewhat familiar with JavaScript and that you have used JavaScript functions to create simple objects.

+ +

Linguagens com base em classe versus protótipo

+ +

Class-based object-oriented languages, such as Java and C++, are founded on the concept of two distinct entities: classes and instances.

+ + + +

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 prototypical object, 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 prototype for another object, allowing the second object to share the first object's properties.

+ +

Definição de uma classe

+ +

In class-based languages, you define a class in a separate class definition. In that definition you can specify special methods, called constructors, 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 new operator in association with the constructor method to create class instances.

+ +

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 new operator with a constructor function to create a new object.

+ +

Subclasses e sucessão

+ +

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 subclass 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 Employee class includes only the name and dept properties, and Manager is a subclass of Employee that adds the reports property. In this case, an instance of the Manager class would have all three properties: name, dept, and reports.

+ +

JavaScript implements inheritance by allowing you to associate a prototypical object with any constructor function. So, you can create exactly the EmployeeManager example, but you use slightly different terminology. First you define the Employee constructor function, specifying the name and dept properties. Next, you define the Manager constructor function, calling the Employee constructor and specifying the reports property. Finally, you assign a new object derived from Employee.prototype as the prototype for the Manager constructor function. Then, when you create a new Manager, it inherits the name and dept properties from the Employee object.

+ +

Adição e remoção de propriedades

+ +

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.

+ +

Resumo das diferenças

+ +

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.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Comparison of class-based (Java) and prototype-based (JavaScript) object systems
Com base em Classe (Java)Com base em Protótipo (JavaScript)
Class and instance are distinct entities.All objects can inherit from another object.
Define a class with a class definition; instantiate a class with constructor methods.Define and create a set of objects with constructor functions.
Create a single object with the new operator.Same.
Construct an object hierarchy by using class definitions to define subclasses of existing classes.Construct an object hierarchy by assigning an object as the prototype associated with a constructor function.
Inherit properties by following the class chain.Inherit properties by following the prototype chain.
Class definition specifies all properties of all instances of a class. Cannot add properties dynamically at run time.Constructor function or prototype specifies an initial set of properties. Can add or remove properties dynamically to individual objects or to the entire set of objects.
+ +

The employee example

+ +

The remainder of this chapter uses the employee hierarchy shown in the following figure.

+ +
+
+

A simple object hierarchy with the following objects:

+ +

+
+ +
+
    +
  • Employee has the properties name (whose value defaults to the empty string) and dept (whose value defaults to "general").
  • +
  • Manager is based on Employee. It adds the reports property (whose value defaults to an empty array, intended to have an array of Employee objects as its value).
  • +
  • WorkerBee is also based on Employee. It adds the projects property (whose value defaults to an empty array, intended to have an array of strings as its value).
  • +
  • SalesPerson is based on WorkerBee. It adds the quota property (whose value defaults to 100). It also overrides the dept property with the value "sales", indicating that all salespersons are in the same department.
  • +
  • Engineer is based on WorkerBee. It adds the machine property (whose value defaults to the empty string) and also overrides the dept property with the value "engineering".
  • +
+
+
+ +

Criação de hierarquia

+ +

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.

+ +

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.

+ +

In a real application, you would probably define constructors that allow you to provide property values at object creation time (see More flexible constructors for information). For now, these simple definitions demonstrate how the inheritance occurs.

+ +

The following Java and JavaScript Employee 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 strongly typed language while JavaScript is a weakly typed language).

+ +
+

JavaScript

+ +
function Employee() {
+  this.name = "";
+  this.dept = "general";
+}
+
+ +

Java

+ +
public class Employee {
+   public String name = "";
+   public String dept = "general";
+}
+
+
+ +

The Manager and WorkerBee 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 prototype 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.

+ +
+

JavaScript

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

Java

+ +
public class Manager extends Employee {
+   public Employee[] reports = new Employee[0];
+}
+
+
+
+public class WorkerBee extends Employee {
+   public String[] projects = new String[0];
+}
+
+
+
+
+ +

The Engineer and SalesPerson definitions create objects that descend from WorkerBee and hence from Employee. 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 dept property with new values specific to these objects.

+ +
+

JavaScript

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

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 = "";
+}
+
+
+
+ +

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.

+ +
+

Nota: The term instance 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 jane is an instance of Engineer. Similarly, although the terms parent, child, ancestor, and descendant do not have formal meanings in JavaScript; you can use them informally to refer to objects higher or lower in the prototype chain.

+
+ +

Criação de objetos com definições simples

+ +
+

Hierarquia do objeto

+ +

The following hierarchy is created using the code on the right side.

+ +

+ +

 

+ +

individual objects

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

Propriedades do objeto

+ +

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.

+ +

Propriedades de sucessão

+ +

Suppose you create the mark object as a WorkerBee with the following statement:

+ +
var mark = new WorkerBee;
+
+ +

When JavaScript sees the new operator, it creates a new generic object and passes this new object as the value of the this keyword to the WorkerBee constructor function. The constructor function explicitly sets the value of the projects property, and implicitly sets the value of the internal __proto__ property to the value of WorkerBee.prototype. (That property name has two underscore characters at the front and two at the end.) The __proto__ 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 mark to that object.

+ +

This process does not explicitly put values in the mark object (local values) for the properties that mark 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 __proto__ 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 mark object has the following properties and values:

+ +
mark.name = "";
+mark.dept = "general";
+mark.projects = [];
+
+ +

The mark object inherits values for the name and dept properties from the prototypical object in mark.__proto__. It is assigned a local value for the projects property by the WorkerBee constructor. This gives you inheritance of properties and their values in JavaScript. Some subtleties of this process are discussed in Property inheritance revisited.

+ +

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 WorkerBee. You can, of course, change the values of any of these properties. So, you could give specific information for mark as follows:

+ +
mark.name = "Doe, Mark";
+mark.dept = "admin";
+mark.projects = ["navigator"];
+ +

Adição de propriedades

+ +

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:

+ +
mark.bonus = 3000;
+
+ +

Now, the mark object has a bonus property, but no other WorkerBee has this property.

+ +

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 specialty property to all employees with the following statement:

+ +
Employee.prototype.specialty = "none";
+
+ +

As soon as JavaScript executes this statement, the mark object also has the specialty property with the value of "none". The following figure shows the effect of adding this property to the Employee prototype and then overriding it for the Engineer prototype.

+ +


+ Adding properties

+ +

Mais construtores flexíveis

+ +

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.

+ +


+ Specifying properties in a constructor, take 1

+ +

The following table shows the Java and JavaScript definitions for these objects.

+ +
+

JavaScript

+ +

Java

+
+ +
+
function Employee (name, dept) {
+  this.name = name || "";
+  this.dept = dept || "general";
+}
+
+ +

 

+ +

 

+ +

 

+ +

 

+ +

 

+ +
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;
+   }
+}
+
+
+ +
+
function WorkerBee (projs) {
+
+ this.projects = projs || [];
+}
+WorkerBee.prototype = new Employee;
+
+ +

 

+ +

 

+ +

 

+ +
public class WorkerBee extends Employee {
+   public String[] projects;
+   public WorkerBee () {
+      this(new String[0]);
+   }
+   public WorkerBee (String[] projs) {
+      projects = projs;
+   }
+}
+
+
+ +
+
+function Engineer (mach) {
+   this.dept = "engineering";
+   this.machine = mach || "";
+}
+Engineer.prototype = new WorkerBee;
+
+ +

 

+ +

 

+ +

 

+ +
public class Engineer extends WorkerBee {
+   public String machine;
+   public Engineer () {
+      dept = "engineering";
+      machine = "";
+   }
+   public Engineer (String mach) {
+      dept = "engineering";
+      machine = mach;
+   }
+}
+
+
+ +

These JavaScript definitions use a special idiom for setting default values:

+ +
this.name = name || "";
+
+ +

The JavaScript logical OR operator (||) 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 name has a useful value for the name property. If it does, it sets this.name to that value. Otherwise, it sets this.name to the empty string. This chapter uses this idiom for brevity; however, it can be puzzling at first glance.

+ +
+

Note: This may not work as expected if the constructor function is called with arguments which convert to false (like 0 (zero) and empty string (""). In this case the default value will be chosen.

+
+ +

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 Engineer:

+ +
var jane = new Engineer("belau");
+
+ +

Jane's properties are now:

+ +
jane.name == "";
+jane.dept == "engineering";
+jane.projects == [];
+jane.machine == "belau"
+
+ +

Notice that with these definitions, you cannot specify an initial value for an inherited property such as name. If you want to specify an initial value for inherited properties in JavaScript, you need to add more code to the constructor function.

+ +

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.

+ +


+ Specifying properties in a constructor, take 2

+ +

Let's look at one of these definitions in detail. Here's the new definition for the Engineer constructor:

+ +
function Engineer (name, projs, mach) {
+  this.base = WorkerBee;
+  this.base(name, "engineering", projs);
+  this.machine = mach || "";
+}
+
+ +

Suppose you create a new Engineer object as follows:

+ +
var jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau");
+
+ +

JavaScript follows these steps:

+ +
    +
  1. The new operator creates a generic object and sets its __proto__ property to Engineer.prototype.
  2. +
  3. The new operator passes the new object to the Engineer constructor as the value of the this keyword.
  4. +
  5. The constructor creates a new property called base for that object and assigns the value of the WorkerBee constructor to the base property. This makes the WorkerBee constructor a method of the Engineer object.The name of the base property is not special. You can use any legal property name; base is simply evocative of its purpose.
  6. +
  7. +

    The constructor calls the base method, passing as its arguments two of the arguments passed to the constructor ("Doe, Jane" and ["navigator", "javascript"]) and also the string "engineering". Explicitly using "engineering" in the constructor indicates that all Engineer objects have the same value for the inherited dept property, and this value overrides the value inherited from Employee.

    +
  8. +
  9. Because base is a method of Engineer, within the call to base, JavaScript binds the this keyword to the object created in Step 1. Thus, the WorkerBee function in turn passes the "Doe, Jane" and "engineering" arguments to the Employee constructor function. Upon return from the Employee constructor function, the WorkerBee function uses the remaining argument to set the projects property.
  10. +
  11. Upon return from the base method, the Engineer constructor initializes the object's machine property to "belau".
  12. +
  13. Upon return from the constructor, JavaScript assigns the new object to the jane variable.
  14. +
+ +

You might think that, having called the WorkerBee constructor from inside the Engineer constructor, you have set up inheritance appropriately for Engineer objects. This is not the case. Calling the WorkerBee constructor ensures that an Engineer object starts out with the properties specified in all constructor functions that are called. However, if you later add properties to the Employee or WorkerBee prototypes, those properties are not inherited by the Engineer object. For example, assume you have the following statements:

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

The jane object does not inherit the specialty property. You still need to explicitly set up the prototype to ensure dynamic inheritance. Assume instead you have these statements:

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

Now the value of the jane object's specialty property is "none".

+ +

Another way of inheriting is by using the call() / apply() methods. Below are equivalent:

+ +
+
function Engineer (name, projs, mach) {
+  this.base = WorkerBee;
+  this.base(name, "engineering", projs);
+  this.machine = mach || "";
+}
+
+ +
function Engineer (name, projs, mach) {
+  WorkerBee.call(this, name, "engineering", projs);
+  this.machine = mach || "";
+}
+
+
+ +

Using the javascript call() method makes a cleaner implementation because the base is not needed anymore.

+ +

Sucessão de propriedade revisitada

+ +

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.

+ +

Valores locais versus sucedidos

+ +

When you access an object property, JavaScript performs these steps, as described earlier in this chapter:

+ +
    +
  1. Check to see if the value exists locally. If it does, return that value.
  2. +
  3. If there is not a local value, check the prototype chain (using the __proto__ property).
  4. +
  5. If an object in the prototype chain has a value for the specified property, return that value.
  6. +
  7. If no such property is found, the object does not have the property.
  8. +
+ +

The outcome of these steps depends on how you define things along the way. The original example had these definitions:

+ +
function Employee () {
+  this.name = "";
+  this.dept = "general";
+}
+
+function WorkerBee () {
+  this.projects = [];
+}
+WorkerBee.prototype = new Employee;
+
+ +

With these definitions, suppose you create amy as an instance of WorkerBee with the following statement:

+ +
var amy = new WorkerBee;
+
+ +

The amy object has one local property, projects. The values for the name and dept properties are not local to amy and so derive from the amy object's __proto__ property. Thus, amy has these property values:

+ +
amy.name == "";
+amy.dept == "general";
+amy.projects == [];
+
+ +

Now suppose you change the value of the name property in the prototype associated with Employee:

+ +
Employee.prototype.name = "Unknown"
+
+ +

At first glance, you might expect that new value to propagate down to all the instances of Employee. However, it does not.

+ +

When you create any instance of the Employee object, that instance gets a local value for the name property (the empty string). This means that when you set the WorkerBee prototype by creating a new Employee object, WorkerBee.prototype has a local value for the name property. Therefore, when JavaScript looks up the name property of the amy object (an instance of WorkerBee), JavaScript finds the local value for that property in WorkerBee.prototype. It therefore does not look further up the chain to Employee.prototype.

+ +

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:

+ +
function Employee () {
+  this.dept = "general";
+}
+Employee.prototype.name = "";
+
+function WorkerBee () {
+  this.projects = [];
+}
+WorkerBee.prototype = new Employee;
+
+var amy = new WorkerBee;
+
+Employee.prototype.name = "Unknown";
+
+ +

In this case, the name property of amy becomes "Unknown".

+ +

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.

+ +

Determining instance relationships

+ +

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 __proto__. This continues recursively; the process is called "lookup in the prototype chain".

+ +

The special property __proto__ is set when an object is constructed; it is set to the value of the constructor's prototype property. So the expression new Foo() creates an object with __proto__ == Foo.prototype. Consequently, changes to the properties of Foo.prototype alters the property lookup for all objects that were created by new Foo().

+ +

Every object has a __proto__ object property (except Object); every function has a prototype object property. So objects can be related by 'prototype inheritance' to other objects. You can test for inheritance by comparing an object's __proto__ to a function's prototype object. JavaScript provides a shortcut: the instanceof operator tests an object against a function and returns true if the object inherits from the function prototype. For example,

+ +
var f = new Foo();
+var isTrue = (f instanceof Foo);
+ +

For a more detailed example, suppose you have the same set of definitions shown in Inheriting properties. Create an Engineer object as follows:

+ +
var chris = new Engineer("Pigman, Chris", ["jsd"], "fiji");
+
+ +

With this object, the following statements are all true:

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

Given this, you could write an instanceOf function as follows:

+ +
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;
+}
+
+ +
Note: 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.
+ +

Using the instanceOf function defined above, these expressions are true:

+ +
instanceOf (chris, Engineer)
+instanceOf (chris, WorkerBee)
+instanceOf (chris, Employee)
+instanceOf (chris, Object)
+
+ +

But the following expression is false:

+ +
instanceOf (chris, SalesPerson)
+
+ +

Informação global nos construtores

+ +

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 Employee:

+ +
var idCounter = 1;
+
+function Employee (name, dept) {
+   this.name = name || "";
+   this.dept = dept || "general";
+   this.id = idCounter++;
+}
+
+ +

With this definition, when you create a new Employee, the constructor assigns it the next ID in sequence and then increments the global ID counter. So, if your next statement is the following, victoria.id is 1 and harry.id is 2:

+ +
var victoria = new Employee("Pigbert, Victoria", "pubs")
+var harry = new Employee("Tschopik, Harry", "sales")
+
+ +

At first glance that seems fine. However, idCounter gets incremented every time an Employee object is created, for whatever purpose. If you create the entire Employee hierarchy shown in this chapter, the Employee constructor is called every time you set up a prototype. Suppose you have the following code:

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

Further assume that the definitions omitted here have the base property and call the constructor above them in the prototype chain. In this case, by the time the mac object is created, mac.id is 5.

+ +

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:

+ +
function Employee (name, dept) {
+   this.name = name || "";
+   this.dept = dept || "general";
+   if (name)
+      this.id = idCounter++;
+}
+
+ +

When you create an instance of Employee 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 Employee to get an assigned id, you must specify a name for the employee. In this example, mac.id would be 1.

+ +

No multiple inheritance

+ +

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.

+ +

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.

+ +

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:

+ +
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")
+
+ +

Further assume that the definition of WorkerBee is as used earlier in this chapter. In this case, the dennis object has these properties:

+ +
dennis.name == "Doe, Dennis"
+dennis.dept == "engineering"
+dennis.projects == ["collabra"]
+dennis.machine == "hugo"
+dennis.hobby == "scuba"
+
+ +

So dennis does get the hobby property from the Hobbyist constructor. However, assume you then add a property to the Hobbyist constructor's prototype:

+ +
Hobbyist.prototype.equipment = ["mask", "fins", "regulator", "bcd"]
+
+ +

The dennis object does not inherit this new property.

+ +
{{PreviousNext("Web/JavaScript/Guide/Working_with_Objects", "Web/JavaScript/Guide/Iterators_and_Generators")}}
diff --git a/files/pt-pt/web/javascript/guide/grammar_and_types/index.html b/files/pt-pt/web/javascript/guide/grammar_and_types/index.html new file mode 100644 index 0000000000..109bd99fe4 --- /dev/null +++ b/files/pt-pt/web/javascript/guide/grammar_and_types/index.html @@ -0,0 +1,641 @@ +--- +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 +--- +
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Introduction", "Web/JavaScript/Guide/Control_flow_and_error_handling")}}
+ +

Este capítulo discute a gramática básica do JavaScript, declarações de variáveis, tipos de dados e literais.

+ +

Básicos

+ +

JavaScript borrows most of its syntax from Java, but is also influenced by Awk, Perl and Python.

+ +

JavaScript is case-sensitive and uses the Unicode character set.

+ +

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 (ASI) 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 lexical grammar.

+ +

Comentários

+ +

The syntax of comments is the same as in C++ and in many other languages:

+ +
// a one line comment
+
+/* this is a longer,
+   multi-line comment
+ */
+
+/* You can't, however, /* nest comments */ SyntaxError */
+ +

Declarações

+ +

There are three kinds of declarations in JavaScript.

+ +
+
{{jsxref("Statements/var", "var")}}
+
Declares a variable, optionally initializing it to a value.
+
{{experimental_inline}} {{jsxref("Statements/let", "let")}}
+
Declares a block scope local variable, optionally initializing it to a value.
+
{{experimental_inline}} {{jsxref("Statements/const", "const")}}
+
Declares a read-only named constant.
+
+ +

Variáveis

+ +

You use variables as symbolic names for values in your application. The names of variables, called {{Glossary("Identifier", "identifiers")}}, conform to certain rules.

+ +

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).

+ +

You can use ISO 8859-1 or Unicode letters such as å and ü in identifiers. You can also use the Unicode escape sequences as characters in identifiers.

+ +

Some examples of legal names are Number_hits, temp99, and _name.

+ +

Declararação de variáveis

+ +

You can declare a variable in three ways:

+ + + +

Avaliação de variáveis

+ +

A variable declared using the var statement with no initial value specified has the value {{jsxref("undefined")}}.

+ +

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:

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

You can use undefined to determine whether a variable has a value. In the following code, the variable input is not assigned a value, and the if statement evaluates to true.

+ +
var input;
+if(input === undefined){
+  doThis();
+} else {
+  doThat();
+}
+
+ +

The undefined value behaves as false when used in a boolean context. For example, the following code executes the function myFunction because the myArray element is undefined:

+ +
var myArray = [];
+if (!myArray[0]) myFunction();
+
+ +

The undefined value converts to NaN when used in numeric context.

+ +
var a;
+a + 2;  // Evaluates to NaN
+ +

When you evaluate a {{jsxref("null")}} variable, the null value behaves as 0 in numeric contexts and as false in boolean contexts. For example:

+ +
var n = null;
+console.log(n * 32); // Will log 0 to the console
+
+ +

Variable scope

+ +

When you declare a variable outside of any function, it is called a global 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 local variable, because it is available only within that function.

+ +

JavaScript before ECMAScript 2015 does not have block statement scope; rather, a variable declared within a block is local to the function (or global scope) that the block resides within. For example the following code will log 5, because the scope of x is the function (or global context) within which x is declared, not the block, which in this case is an if statement.

+ +
if (true) {
+  var x = 5;
+}
+console.log(x);  // 5
+
+ +

This behavior changes, when using the let declaration introduced in ECMAScript 2015.

+ +
if (true) {
+  let y = 5;
+}
+console.log(y);  // ReferenceError: y is not defined
+
+ +

Variable hoisting

+ +

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 hoisting; 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 undefined. So even if you declare and initialize after you use or refer to this variable, it will still return undefined.

+ +
/**
+ * 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";
+})();
+
+ +

The above examples will be interpreted the same as:

+ +
/**
+ * 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";
+})();
+
+ +

Because of hoisting, all var 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.

+ +

In ECMAScript 2015, let (const) will not hoist the variable to the top of the block. However, referencing the variable in the block before the variable declaration results in a ReferenceError. The variable is in a "temporal dead zone" from the start of the block until the declaration is processed.

+ +
console.log(x); // ReferenceError
+let x = 3;
+ +

Variáveis gGlobais

+ +

Global variables are in fact properties of the global object. In web pages the global object is {{domxref("window")}}, so you can set and access global variables using the window.variable syntax.

+ +

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 phoneNumber is declared in a document, you can refer to this variable from an iframe as parent.phoneNumber.

+ +

Constantes

+ +

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.

+ +
const PI = 3.14;
+
+ +

A constant cannot change value through assignment or be re-declared while the script is running. It has to be initialized to a value.

+ +

The scope rules for constants are the same as those for let block scope variables. If the const keyword is omitted, the identifier is assumed to represent a variable.

+ +

You cannot declare a constant with the same name as a function or variable in the same scope. For example:

+ +
// THIS WILL CAUSE AN ERROR
+function f() {};
+const f = 5;
+
+// THIS WILL CAUSE AN ERROR ALSO
+function f() {
+  const g = 5;
+  var g;
+
+  //statements
+}
+
+ +

However, object attributes are not protected, so the following statement is executed without problems.

+ +
const MY_OBJECT = {"key": "value"};
+MY_OBJECT.key = "otherValue";
+ +

Estruturas e tipode dados

+ +

tipos de dados

+ +

The latest ECMAScript standard defines seven data types:

+ + + +

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.

+ +

Conversão de tipo de dados

+ +

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:

+ +
var answer = 42;
+
+ +

And later, you could assign the same variable a string value, for example:

+ +
answer = "Thanks for all the fish...";
+
+ +

Because JavaScript is dynamically typed, this assignment does not cause an error message.

+ +

In expressions involving numeric and string values with the + operator, JavaScript converts numeric values to strings. For example, consider the following statements:

+ +
x = "The answer is " + 42 // "The answer is 42"
+y = 42 + " is the answer" // "42 is the answer"
+
+ +

In statements involving other operators, JavaScript does not convert numeric values to strings. For example:

+ +
"37" - 7 // 30
+"37" + 7 // "377"
+
+ +

Conversão de strings para números

+ +

In the case that a value representing a number is in memory as a string, there are methods for conversion.

+ + + +

parseInt will only return whole numbers, so its use is diminished for decimals. Additionally, a best practice for parseInt is to always include the radix parameter. The radix parameter is used to specify which numerical system is to be used.

+ +

An alternative method of retrieving a number from a string is with the + (unary plus) operator:

+ +
"1.1" + "1.1" = "1.11.1"
+(+"1.1") + (+"1.1") = 2.2
+// Note: the parentheses are added for clarity, not required.
+ +

Literais

+ +

You use literals to represent values in JavaScript. These are fixed values, not variables, that you literally provide in your script. This section describes the following types of literals:

+ + + +

Literais de tabela

+ +

An array literal is a list of zero or more expressions, each of which represents an array element, enclosed in square brackets ([]). 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.

+ +

The following example creates the coffees array with three elements and a length of three:

+ +
var coffees = ["French Roast", "Colombian", "Kona"];
+
+ +
+

Note : An array literal is a type of object initializer. See Using Object Initializers.

+
+ +

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.

+ +

Array literals are also Array objects. See {{jsxref("Array")}} and Indexed collections for details on Array objects.

+ +

Extra commas in array literals

+ +

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 undefined for the unspecified elements. The following example creates the fish array:

+ +
var fish = ["Lion", , "Angel"];
+
+ +

This array has two elements with values and one empty element (fish[0] is "Lion", fish[1] is undefined, and fish[2] is "Angel").

+ +

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 myList[3]. All other commas in the list indicate a new element.

+ +
+

Nota : Trailing commas can create errors in older browser versions and it is a best practice to remove them.

+
+ +
var myList = ['home', , 'school', ];
+
+ +

In the following example, the length of the array is four, and myList[0] and myList[2] are missing.

+ +
var myList = [ , 'home', , 'school'];
+
+ +

In the following example, the length of the array is four, and myList[1] and myList[3] are missing. Only the last comma is ignored.

+ +
var myList = ['home', , 'school', , ];
+
+ +

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 undefined will increase your code's clarity and maintainability.

+ +

Lietrais boolianas

+ +

The Boolean type has two literal values: true and false.

+ +

Do not confuse the primitive Boolean values true and false 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.

+ +

Íntegros

+ +

Integers can be expressed in decimal (base 10), hexadecimal (base 16), octal (base 8) and binary (base 2).

+ + + +

Some examples of integer literals are:

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

For more information, see Numeric literals in the Lexical grammar reference.

+ +

Literais de ponto flutuante

+ +

A floating-point literal can have the following parts:

+ + + +

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").

+ +

More succinctly, the syntax is:

+ +
[(+|-)][digits][.digits][(E|e)[(+|-)]digits]
+
+ +

For example:

+ +
3.1415926
+-.123456789
+-3.1E+12
+.1e-23
+
+ +

Literais de objeto

+ +

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.

+ +

The following is an example of an object literal. The first element of the car object defines a property, myCar, and assigns to it a new string, "Saturn"; the second element, the getCar property, is immediately assigned the result of invoking the function (carTypes("Honda")); the third element, the special property, uses an existing variable (sales).

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

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.

+ +
var car = { manyCars: {a: "Saab", "b": "Jeep"}, 7: "Mazda" };
+
+console.log(car.manyCars.b); // Jeep
+console.log(car[7]); // Mazda
+
+ +

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 (.) property, but can be accessed and set with the array-like notation("[]").

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

In ES2015, object literals are extended to support setting the prototype at construction, shorthand for foo: foo 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.

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

Por favor, note:

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

RegExp literals

+ +

A regex literal is a pattern enclosed between slashes. The following is an example of an regex literal.

+ +
var re = /ab+c/;
+ +

Lietrais de string

+ +

A string literal is zero or more characters enclosed in double (") or single (') 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:

+ +
"foo"
+'bar'
+"1234"
+"one line \n another line"
+"John's cat"
+
+ +

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 String.length property with a string literal:

+ +
console.log("John's cat".length)
+// Will print the number of symbols in the string including whitespace.
+// In this case, 10.
+
+ +

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.

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

You should use string literals unless you specifically need to use a String object. See {{jsxref("String")}} for details on String objects.

+ +

Using special characters in strings

+ +

In addition to ordinary characters, you can also include special characters in strings, as shown in the following example.

+ +
"one line \n another line"
+
+ +

The following table lists the special characters that you can use in JavaScript strings.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Table: JavaScript special characters
CáraterSignificado
\0Null Byte
\bBackspace
\fForm feed
\nNew line
\rCarriage return
\tTab
\vVertical tab
\'Apostrophe or single quote
\"Double quote
\\Backslash character
\XXXThe character with the Latin-1 encoding specified by up to three octal digits XXX between 0 and 377. For example, \251 is the octal sequence for the copyright symbol.
\xXXThe character with the Latin-1 encoding specified by the two hexadecimal digits XX between 00 and FF. For example, \xA9 is the hexadecimal sequence for the copyright symbol.
\uXXXXThe Unicode character specified by the four hexadecimal digits XXXX. For example, \u00A9 is the Unicode sequence for the copyright symbol. See Unicode escape sequences.
\u{XXXXX}Unicode code point escapes. For example, \u{2F804} is the same as the simple Unicode escapes \uD87E\uDC04.
+ +

Escaping characters

+ +

For characters not listed in the table, a preceding backslash is ignored, but this usage is deprecated and should be avoided.

+ +

You can insert a quotation mark inside a string by preceding it with a backslash. This is known as escaping the quotation mark. For example:

+ +
var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service.";
+console.log(quote);
+
+ +

The result of this would be:

+ +
He read "The Cremation of Sam McGee" by R.W. Service.
+
+ +

To include a literal backslash inside a string, you must escape the backslash character. For example, to assign the file path c:\temp to a string, use the following:

+ +
var home = "c:\\temp";
+
+ +

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.

+ +
var str = "this string \
+is broken \
+across multiple\
+lines."
+console.log(str);   // this string is broken across multiplelines.
+
+ +

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:

+ +
var poem =
+"Roses are red,\n\
+Violets are blue.\n\
+Sugar is sweet,\n\
+and so is foo."
+
+ +

Mais informação

+ +

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:

+ + + +

In the next chapter, we will have a look at control flow constructs and error handling.

+ +

{{PreviousNext("Web/JavaScript/Guide/Introduction", "Web/JavaScript/Guide/Control_flow_and_error_handling")}}

diff --git a/files/pt-pt/web/javascript/guide/index.html b/files/pt-pt/web/javascript/guide/index.html new file mode 100644 index 0000000000..aec08fb7ad --- /dev/null +++ b/files/pt-pt/web/javascript/guide/index.html @@ -0,0 +1,123 @@ +--- +title: Guia de JavaScript +slug: Web/JavaScript/Guia +tags: + - Guía + - JavaScript + - 'l10n:prioridade' +translation_of: Web/JavaScript/Guide +--- +
{{jsSidebar("JavaScript Guide")}}
+ +

The JavaScript Guide shows you how to use JavaScript and gives an overview of the language. If you want to get started with JavaScript or programming in general, consult the articles in the learning area. If you need exhaustive information about a language feature, have a look at the JavaScript reference.

+ +

Capítulos

+ +

This Guide is divided into several chapters:

+ + + + + + + + + +

{{Next("Web/JavaScript/Guide/Introduction")}}

diff --git a/files/pt-pt/web/javascript/guide/introduction/index.html b/files/pt-pt/web/javascript/guide/introduction/index.html new file mode 100644 index 0000000000..f77bb74379 --- /dev/null +++ b/files/pt-pt/web/javascript/guide/introduction/index.html @@ -0,0 +1,137 @@ +--- +title: Introdução +slug: Web/JavaScript/Guia/Introdução +tags: + - Guía + - JavaScript +translation_of: Web/JavaScript/Guide/Introduction +--- +
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide", "Web/JavaScript/Guide/Grammar_and_types")}}
+ +

Este capítulo apresenta a linguagem JavaScript e discuste alguns dos seus conceitos fundamentais.

+ +

O que você já deveria saber

+ +

Este guia assume que você possuí os seguintes conhecimentos:

+ + + +

Onde encontrar informação sobre JavaScript?

+ +

A documentação de JavaScript no MDN incluí o seguinte:

+ + + +

Se for iniciante em JavaScript, comece lendo alguns dos artigos na área de aprendizagem e o  Guia de JavaScript. Assim que compreender os fundamentos da linguagem, pode consultar a Referência de JavaScript para obter mais detalhes sobre objetos individuais e declarações.

+ +

O que é JavaScript?

+ +

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.

+ +

O JavaScript contém uma biblioteca padrão de objetos, tais como ArrayDateMath, 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:

+ + + +

JavaScript e Java

+ +

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.

+ +

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.

+ +

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.

+ +

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.

+ +

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.

+ + + + + + + + + + + + + + + + + + + + + + + +
JavaScript comparado com Java
JavaScriptJava
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.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.
Variable data types are not declared (dynamic typing).Variable data types must be declared (static typing).
Cannot automatically write to hard disk.Can automatically write to hard disk.
+ +

For more information on the differences between JavaScript and Java, see the chapter Details of the object model.

+ +

JavaScript e a especificação ECMAScript

+ +

JavaScript is standardized at Ecma International — 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 New in JavaScript to learn more about different versions of JavaScript and ECMAScript specification editions.

+ +

The ECMA-262 standard is also approved by the ISO (International Organization for Standardization) as ISO-16262. You can also find the specification on the Ecma International website. The ECMAScript specification does not describe the Document Object Model (DOM), which is standardized by the World Wide Web Consortium (W3C) and/or WHATWG (Web Hypertext Application Technology Working Group). 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 JavaScript technologies overview.

+ +

Documentação JavaScript versus especificação  ECMAScript

+ +

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).

+ +

The ECMAScript document is not intended to help script programmers; use the JavaScript documentation for information on writing scripts.

+ +

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.

+ +

The JavaScript documentation describes aspects of the language that are appropriate for a JavaScript programmer.

+ +

Começar com JavaScript

+ +

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.

+ +

There are two tools built into Firefox that are useful for experimenting with JavaScript: the Web Console and Scratchpad.

+ +

A Consola da Web

+ +

A Consola da Web shows you information about the currently loaded Web page, and also includes a command line that you can use to execute JavaScript expressions in the current page.

+ +

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:

+ +

+ +

Scratchpad

+ +

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 Scratchpad is a better tool.

+ +

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.

+ +

+ +

Olá mundo

+ +

To get started with writing JavaScript, open the Scratchpad and write your first "Hello world" JavaScript code:

+ +
function greetMe(yourName) {
+  alert("Hello " + yourName);
+}
+
+greetMe("World");
+
+ +

Select the code in the pad and hit Ctrl+R to watch it unfold in your browser!

+ +

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.

+ +

{{PreviousNext("Web/JavaScript/Guide", "Web/JavaScript/Guide/Grammar_and_types")}}

diff --git a/files/pt-pt/web/javascript/memory_management/index.html b/files/pt-pt/web/javascript/memory_management/index.html new file mode 100644 index 0000000000..56bfec0f7f --- /dev/null +++ b/files/pt-pt/web/javascript/memory_management/index.html @@ -0,0 +1,187 @@ +--- +title: Gestão de memória +slug: Web/JavaScript/Gestao_Memoria +tags: + - Desempenho + - JavaScript + - memoria +translation_of: Web/JavaScript/Memory_Management +--- +
{{JsSidebar("Advanced")}}
+ +

Introdução

+ +

Linguagens de baixo nível, como o C, têm funções pimitivas de gestão de memória, como por exemplo, malloc() e free(). Por outro lado, os valores em JavaScript são alocados quando coisas (objetos, variáveis de texto, etc.) são criadas e "automaticamente" libertadas da memória quando deixam de ser utilizadas. O último processo é chamado de coleção do lixo. Este "automatismo" é uma fonte de mal entendidos e transmite aos programadores de JavaScript ( e aos de outras linguagens de alto nível ) a impressão de que podem decidir não se preocupar com a gestão da memória. Isto é uma erro.

+ +

Ciclo da duração da memória

+ +

Independentemente da linguagem de programação, o ciclo da duração da memória é praticamente sempre o mesmo:

+ +
    +
  1. Alocação da memória necessária
  2. +
  3. Utilização da memória alocada ( leitura, escrita )
  4. +
  5. Libertar a memória alocada quando já não é necessária
  6. +
+ +

A segunda etapa é explícita em todas as linguagens. A primeira e a última etapa são explícitas em linguagens de baixo nível mas são, na sua maioria, implícitas em linguagens de alto nível como o JavaScript.

+ +

Alocação no JavaScript

+ +

Inicialização do valor

+ +

Com o intuito de não incomodar o programador com alocações, o JavaScript fá-lo juntamente com a declaração de valores.

+ +
var n = 123; // alocação da memória para um número
+var s = 'azerty'; // alocação de memória para um texto
+
+var o = {
+  a: 1,
+  b: null
+}; // alocação de memória para um objeto e o seu conteúdo
+
+// (similar ao objeto) alocação de memória para a matriz e
+// os seus valores
+var a = [1, null, 'abra'];
+
+function f(a) {
+  return a + 2;
+} // alocação de uma função (que é um objeto que pode ser chamado)
+
+// Expressões de funções também alocam um objeto
+someElement.addEventListener('click', function() {
+  someElement.style.backgroundColor = 'blue';
+}, false);
+
+ +

Alocação através de chamadas de funções

+ +

Algumas chamadas de funções resultam na alocação de um objeto.

+ +
var d = new Date(); // alocação de um objeto Date
+
+var e = document.createElement('div'); // alocação de um elemento DOM
+ +

Alguns métodos alocam novos valores ou objetos:

+ +
var s = 'azerty';
+var s2 = s.substr(0, 3); // s2 é uma nova variável de texto
+// Dado que as variáveis de texto são de valor imutável,
+// o JavaScript pode decidir não alocar memória,
+// mas apenas armazenar o intervalo [0, 3].
+
+var a = ['ouais ouais', 'nan nan'];
+var a2 = ['generation', 'nan nan'];
+var a3 = a.concat(a2);
+// nova matriz de 4 elementos resultando
+// da concatenação dos elementos de a e a2
+
+ +

Utilização de valores

+ +

Basicamente, a utilização de valores significa a leitura e a escrita na memória alocada. Isto pode ser feito através da leitura ou escrita do valor de uma variável ou uma propriedade de um objeto ou até a passagem de um argumento para uma função.

+ +

Remoção quando a memória já não é necessária

+ +

A maioria dos problemas de gestão de memória aparecem nesta fase. A tarefa mais difícil é descobrir quando "a memória alocada já não é necessária". Em geral, requer que o programador determine quando, no seu código, este pedaço de memória já não é necessário e a liberte.

+ +

Linguagens de alto nível têm embutidas um pedaço de código chamado "coleção de lixo", cuja tarefa é rastrear a alocação e uso da memória, para detetar quando um pedaço de memória já não é necessário e neste caso, automaticamente libertá-la. Este processo é uma aproximação dado que o problema geral de se saber quando um pedaço da memória é necessário, é indecisível ( não pode ser solucionado por um algoritmo ).

+ +

Coleção de lixo

+ +

Como mencionado anteriormente, o problema geral de automaticamente descobrir quando alguma ocupação de memória "já não é necessária", é indecisível. Como consequência, as coleções de lixo implementam uma restrição à solução para o problema em geral. Esta seção explicará as noções necessárias para se compreender os principais algoritmos da coleção de lixo e as suas limitações.

+ +

Referências

+ +

A noção principal dos algoritmos de coleção de lixo baseiam-se na noção de referência. Dentro do contexto da gestão de memória, um objeto é dito referenciar outro objeto, se o primeiro tiver acesso ao segundo ( quer implicitamente quer explicitamente ). Por exemplo, um objeto JavaScript tem uma referência ao seu protótipo ( referência implícita )  e aos valores das suas propriedades ( referência explícita ).

+ +

Neste contexto, a noção de "objeto" é expandida a algo mais abrangente que um objeto JavaScript e também contém âmbitos de funções ( ou âmbito léxico global ).

+ +

Contagem de referências na coleção de lixo

+ +

Este é o algoritmo mais simples da coleção de lixo. Este algoritmo reduz a definição de "um objeto já não é necessário" para "um objeto já não é referenciado por nenhum outro objeto". Um objeto é considerado coletável para a coleção de lixo se tiver nenhuma referenciação por parte de outro objeto.

+ +

Exemplo

+ +
var o = {
+  a: {
+    b: 2
+  }
+};
+// 2 objetos criados. Um é referenciado por outro como sendo suas propriedades
+// O outro é referenciado por virtude ao ser assignado para a variável 'o'
+// Obviamente, nenhum podem ser coletado pela coleção de lixo
+
+
+var o2 = o; // A variável 'o2' é a segunda coisa que
+            // tem uma referência ao objeto
+o = 1;      // agora, o objeto que era originalmente o 'o' tem uma referência única
+            // corporificada pela variável 'o2'
+
+var oa = o2.a; // referência à propriedade 'a' do objeto.
+               // Este objeto tem agora 2 referências: uma como propriedade,
+               // a outra como variável 'oa'
+
+o2 = 'yo'; // O objeto que era o original 'o' tem agora zero
+           // referências a si próprio. Pode ser coletado para a coleção de lixo
+           // No entanto, a propriedade 'a' ainda é referenciada pela
+           // variável 'oa', logo não pode ser libertado
+
+oa = null; // A propriedade 'a' do objeto original 'o'
+           // tem zero referências a si próprio. Pode ser coletado para a  coleção de lixo.
+
+ +

Limitação: ciclos

+ +

Existe uma limitação no que se refere aos ciclos. No exemplo seguinte, dois objetos são criados e referenciam-se mutuamente, criando um ciclo. Estes sairão do âmbito depois de uma chamada a uma função e como tal, são efetivamente inúteis e podem ser libertados. No entanto, o algoritmo de contagem de referências considera que os dois objetos têm pelo menos uma referenciação; nenhum pode ser coletado para a coleção de lixo .

+ +
function f() {
+  var o = {};
+  var o2 = {};
+  o.a = o2; // o referencia o2
+  o2.a = o; // o2 referencia o
+
+  return 'azerty';
+}
+
+f();
+
+ +

Exemplo de aplicação real

+ +

O Internet Explorer 6 e 7 são conhecidos por terem um coletor de contagem de referenciações de coleções de lixo para os objetos DOM. Os ciclos são um erro comum que podem gerar percas de memória:

+ +
var div;
+window.onload = function() {
+  div = document.getElementById('myDivElement');
+  div.circularReference = div;
+  div.lotsOfData = new Array(10000).join('*');
+};
+
+ +

No exemplo acima, o elemento DOM "myDivElement" tem uma referência circular a si próprio na propriedade "circularReference". Se a propriedade não for explicitamente removida ou anulada, o coletor de contagem de referências da coleção de lixo, irá sempre ter uma referenciação intacta e irá manter o elemento DOM na memória mesmo quando for removido da árvore DOM. Se o elemento DOM contém bastante dados ( ilustrado no exemplo acima com a propriedade "lotsOfData" ), a memória consumida por estes dados nunca será libertada.

+ +

Algoritmo de marcação e limpeza

+ +

Este algoritmo reduz a definição de "um objeto já não é necessário" para "um objeto é inalcançável".

+ +

Este algoritmo assume o conhecimento de um conjunto de objetos chamados "roots" ( em JavaScript, a root - raiz - é um objeto global ). Periodicamente, a coleção de lixo começará pela raíz e procurará todos os objetos que são referenciados a partir desta; depois todos os que são referenciados a partir dos seguintes, etc.. Começando pela raiz, o coletor de lixo irá localizar objetos inalcançáveis; coletando-os.

+ +

Este algoritmo é melhor do que o anterior dado que "um objeto tem zero referenciações" leva a um objeto inalcançável. O contrário não é verdade como vimos nos ciclos.

+ +

Desde 2012, todos os modernos navegadores de Internet contêm um coletor de marcação e limpeza. Todos os melhoramentos feitos na área da coleção de lixo no JavaScript ( generalização / incrementação / concorrência / coleção de lixo paralela ) nos últimos anos são implemetações de melhoramento deste algoritmo, mas não melhoramentos do algoritmo de coleção de lixo em si nem a sua redução à definição de que quando "um objeto já não é necessário".

+ +

Os ciclos já não são um problema.

+ +

No primeiro exemplo acima, depois do retorno da chamada à função, 2 objetos já não são referenciados por algo alcançável no objeto global. Consequentemente, irão ser localizados pelo coletor da coleção de lixo.

+ +

Limitações: os objetos necessitam de ser explicitamente inalcançáveis

+ +

Apesar disto estar marcado como uma limitação, é um caso que raramente ocorre na prática pelo que é por isto que ninguém se preocupa muito com a coleção de lixo.

+ +

Ver também

+ + diff --git "a/files/pt-pt/web/javascript/o_que_\303\251_o_javascript/index.html" "b/files/pt-pt/web/javascript/o_que_\303\251_o_javascript/index.html" deleted file mode 100644 index 4145f9dc58..0000000000 --- "a/files/pt-pt/web/javascript/o_que_\303\251_o_javascript/index.html" +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: O que é o JavaScript -slug: Web/JavaScript/O_que_é_o_JavaScript ---- -

O JavaScript é uma linguagem de programação do lado cliente, ou seja, é processada pelo próprio navegador. -Com o JavaScript podemos criar efeitos especiais para nossas páginas na Web, além -de podermos proporcionar uma maior interatividade com nossos usuários. -O JavaScript é uma linguagem orientada a objetos, ou seja, ela trata todos os elementos da página -como objetos distintos, fascilitando a tarefa da programação. -

Resumindo, o JavaScript é uma poderosa linguagem que deve ser dominada por quem deseja criar páginas Web dinamicas e interativas. -


---rafael.marcondes92@gmail.com 12:39, 14 Julho 2008 (PDT) -

diff --git a/files/pt-pt/web/javascript/reference/about/index.html b/files/pt-pt/web/javascript/reference/about/index.html new file mode 100644 index 0000000000..3b2a79ac32 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/about/index.html @@ -0,0 +1,52 @@ +--- +title: Sobre a referência de JavaScript +slug: Web/JavaScript/Reference/Sobre +tags: + - JavaScript +translation_of: Web/JavaScript/Reference/About +--- +
{{JsSidebar}}
+ +

The JavaScript reference serves as a repository of facts about the JavaScript language. The entire language is described here in detail. As you write JavaScript code, you'll refer to these pages often (thus the title "JavaScript reference"). If you're learning JavaScript, or need help understanding some of its capabilities or features, check out the JavaScript guide.

+ +

The JavaScript language is intended to be used within some larger environment, be it a browser, server-side scripts, or similar. For the most part, this reference attempts to be environment-agnostic and does not target a web browser environment.

+ +

Onde encontrar informação sobre JavaScript

+ +

JavaScript documentation of core language features (pure ECMAScript, for the most part) includes the following:

+ + + +

If you are new to JavaScript, start with the guide. Once you have a firm grasp of the fundamentals, you can use the reference to get more details on individual objects and language constructs.

+ +

Estrutura da referência

+ +

In the JavaScript reference you can find the following chapters:

+ +
+
Standard built-in objects
+
This chapter documents all the JavaScript standard built-in objects, along with their methods and properties.
+
Statements and declarations
+
JavaScript applications consist of statements with an appropriate syntax. A single statement may span multiple lines. Multiple statements may occur on a single line if each statement is separated by a semicolon. This isn't a keyword, but a group of keywords.
+
Expressions and operators
+
This chapter documents all the JavaScript language operators, expressions and keywords.
+
Functions
+
Chapter about JavaScript functions.
+
Classes
+
Chapter about JavaScript classes introduced in ECMAScript 6.
+
Errors
+
Chapter about specific errors, exceptions and warnings thrown by JavaScript.
+
New in JavaScript
+
Chapter about JavaScript version history.
+
+ +

Mais páginas de referência

+ + diff --git a/files/pt-pt/web/javascript/reference/deprecated_and_obsolete_features/index.html b/files/pt-pt/web/javascript/reference/deprecated_and_obsolete_features/index.html new file mode 100644 index 0000000000..9d0ae63c62 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/deprecated_and_obsolete_features/index.html @@ -0,0 +1,289 @@ +--- +title: Funcionalidades obsoletas +slug: Web/JavaScript/Reference/Funcionalidades_obsoletas +tags: + - JavaScript + - Obsoleto +translation_of: Web/JavaScript/Reference/Deprecated_and_obsolete_features +--- +
{{JsSidebar("More")}}
+ +

Esta página lista as funcionalidades de JavaScript que estão obsoletas (ou seja, ainda disponíveis, mas planeadas para remoção) e obsoletas (isto é, não são mais utilizáveis).

+ +

Funcionalidades obsoletas

+ +

Estas funcionalidades obsoletas ainda podem ser utilziadas, mas devem ser utilizadas ​​com cuidado, pois espera-se que estas sejam removidas inteiramente no futuro. Deverá trabalhar para remover a utilização das mesmas do seu código..

+ +

Propriedades de RegExp

+ +

The following properties are deprecated. This does not affect their use in {{jsxref("String.replace", "replacement strings", "", 1)}}:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropriedadesDescrição
{{jsxref("RegExp.n", "$1-$9")}} +

Parenthesized substring matches, if any.
+ Warning: Using these properties can result in problems, since browser extensions can modify them. Avoid them!

+
{{jsxref("RegExp.input", "$_")}}See input.
{{jsxref("RegExp.multiline", "$*")}}See multiline.
{{jsxref("RegExp.lastMatch", "$&")}}See lastMatch.
{{jsxref("RegExp.lastParen", "$+")}}See lastParen.
{{jsxref("RegExp.leftContext", "$`")}}See leftContext.
{{jsxref("RegExp.rightContext", "$'")}}See rightContext.
{{jsxref("RegExp.input", "input")}}The string against which a regular expression is matched.
{{jsxref("RegExp.lastMatch", "lastMatch")}}The last matched characters.
{{jsxref("RegExp.lastParen", "lastParen")}}The last parenthesized substring match, if any.
{{jsxref("RegExp.leftContext", "leftContext")}}The substring preceding the most recent match.
{{jsxref("RegExp.rightContext", "rightContext")}}The substring following the most recent match.
+ +

The following are now properties of RegExp instances, no longer of the RegExp object:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropriedadesDescrição
{{jsxref("RegExp.global", "global")}}Whether or not to test the regular expression against all possible matches in a string, or only against the first.
{{jsxref("RegExp.ignoreCase", "ignoreCase")}}Whether or not to ignore case while attempting a match in a string.
{{jsxref("RegExp.lastIndex", "lastIndex")}}The index at which to start the next match.
{{jsxref("RegExp.multiline", "multiline")}}Whether or not to search in strings across multiple lines.
{{jsxref("RegExp.source", "source")}}The text of the pattern.
+ +

Métodos de egExp

+ + + +

Propriedades de Function

+ + + +

Gerador de Legacy

+ + + +

Iterator

+ + + +

Métodos de Object

+ + + +

Métodos de Date

+ + + +

Functions

+ + + +

Proxy

+ + + +

Sequências de Escape

+ + + +

Métodos de String

+ + + +

Funcionalidades removidas

+ +

Estas funcionalidades obsoletas foram totalmente removidas do JavaScript e não podem mais ser utilizadas a partir da versão indicada do JavaScript.

+ +

Object

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyDescription
{{jsxref("Global_Objects/Object/count", "__count__")}}Returns the number of enumerable properties directly on a user-defined object.
{{jsxref("Global_Objects/Object/Parent", "__parent__")}}Points to an object's context.
{{jsxref("Global_Objects/Object/eval", "Object.prototype.eval()")}}Evaluates a string of JavaScript code in the context of the specified object.
{{jsxref("Object.observe()")}}Asynchronously observing the changes to an object.
{{jsxref("Object.unobserve()")}}Remove observers.
{{jsxref("Object.getNotifier()")}}Creates an object that allows to synthetically trigger a change.
+ +

Function

+ + + + + + + + + + + + +
PropertyDescription
{{jsxref("Global_Objects/Function/arity", "arity")}}Number of formal arguments.
+ +

Array

+ + + + + + + + + + + + + + + + +
PropertyDescription
{{jsxref("Array.observe()")}}Asynchronously observing changes to Arrays.
{{jsxref("Array.unobserve()")}}Remove observers.
+ +

Number

+ + + +

ParallelArray

+ + + +

Statements

+ + + +

E4X

+ +

See E4X for more information.

+ +

Variáveis Sharp

+ +

Consulte Sharp variables in JavaScript para mais informação.

diff --git "a/files/pt-pt/web/javascript/reference/errors/declara\303\247\303\243o_fun\303\247\303\243o_sem_nome/index.html" "b/files/pt-pt/web/javascript/reference/errors/declara\303\247\303\243o_fun\303\247\303\243o_sem_nome/index.html" deleted file mode 100644 index a747257379..0000000000 --- "a/files/pt-pt/web/javascript/reference/errors/declara\303\247\303\243o_fun\303\247\303\243o_sem_nome/index.html" +++ /dev/null @@ -1,113 +0,0 @@ ---- -title: 'Erro de sintaxe: declaração de função precisa de um nome' -slug: Web/JavaScript/Reference/Errors/declaração_função_sem_nome -translation_of: Web/JavaScript/Reference/Errors/Unnamed_function_statement ---- -
{{jsSidebar("Errors")}}
- -

Mensagem

- -
Syntax Error: Expected identifier (Edge)
-SyntaxError: function statement requires a name [Firefox]
-SyntaxError: Unexpected token ( [Chrome]
-
- -

Tipo de erro

- -

{{jsxref("SyntaxError")}}

- -

O que correu mal?

- -

Existe uma declaração de função no código que precisa de um nome. Você deve verficiar como as funções são definidas e se é necessário indicar um nome para a função

- -

Existe uma declaração de função no código que requer um nome. Você precisará verificar como as funções são definidas e se você precisa fornecer um nome para a função, ou se a função em questão precisa ser uma expressão de função, um {{Glossary ("IIFE")}}, ou se o código da função esta colocado corretamente neste contexto.

- -

Exemplos

- -

Declarações vs Expressões

- -

Uma declaração de função precisa de um nome, o código seguinte não funciona:

- -
function () {
-  return 'Hello world';
-}
-// SyntaxError: function statement requires a name
-
- -

É possível usar uma expressão de função (atribuição) como alternativa:

- -
var greet = function() {
-  return 'Hello world';
-};
- -

Ou, a sua função é talvez destinada a ser uma IIFE (Expressão de Função Invocada Imediatamente), que é uma função que é executada assim que é definida. Serão precisos mais alguns parêntises neste caso:

- -
(function () {
-
-})();
- -

Funções com nome

- -

Se você está a usar uma função com identificador, ainda precisará fornecer um nome de função após a palavra-chave da função. O código seguinte não funciona:

- -
function Greeter() {
-  german: function () {
-    return "Moin";
-  }
-}
-// SyntaxError: function statement requires a name
-
- -

O código seguinte irá funcionar por exemplo:

- -
function Greeter() {
-  german: function g() {
-    return "Moin";
-  }
-}
- -

Métodos de objectos

- -

Se você pretendia criar um método de um objeto, você precisará criar um objeto. A sintaxe a seguir sem um nome após a palavra-chave function é válida.

- -
var greeter = {
-  german: function () {
-    return "Moin";
-  }
-};
- -

Sintaxe de Callback

- -

Além disso, verifique a sintaxe ao usar callbacks. Parêntisis e virgurlas podem facilmente se tornar complicados.

- -
promise.then(
-  function() {
-    console.log("success");
-  });
-  function() {
-    console.log("error");
-}
-// SyntaxError: function statement requires a name
-
- -

:

- -
promise.then(
-  function() {
-    console.log("success");
-  },
-  function() {
-    console.log("error");
-  }
-);
-
- -

Veja também

- - diff --git a/files/pt-pt/web/javascript/reference/errors/unnamed_function_statement/index.html b/files/pt-pt/web/javascript/reference/errors/unnamed_function_statement/index.html new file mode 100644 index 0000000000..a747257379 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/errors/unnamed_function_statement/index.html @@ -0,0 +1,113 @@ +--- +title: 'Erro de sintaxe: declaração de função precisa de um nome' +slug: Web/JavaScript/Reference/Errors/declaração_função_sem_nome +translation_of: Web/JavaScript/Reference/Errors/Unnamed_function_statement +--- +
{{jsSidebar("Errors")}}
+ +

Mensagem

+ +
Syntax Error: Expected identifier (Edge)
+SyntaxError: function statement requires a name [Firefox]
+SyntaxError: Unexpected token ( [Chrome]
+
+ +

Tipo de erro

+ +

{{jsxref("SyntaxError")}}

+ +

O que correu mal?

+ +

Existe uma declaração de função no código que precisa de um nome. Você deve verficiar como as funções são definidas e se é necessário indicar um nome para a função

+ +

Existe uma declaração de função no código que requer um nome. Você precisará verificar como as funções são definidas e se você precisa fornecer um nome para a função, ou se a função em questão precisa ser uma expressão de função, um {{Glossary ("IIFE")}}, ou se o código da função esta colocado corretamente neste contexto.

+ +

Exemplos

+ +

Declarações vs Expressões

+ +

Uma declaração de função precisa de um nome, o código seguinte não funciona:

+ +
function () {
+  return 'Hello world';
+}
+// SyntaxError: function statement requires a name
+
+ +

É possível usar uma expressão de função (atribuição) como alternativa:

+ +
var greet = function() {
+  return 'Hello world';
+};
+ +

Ou, a sua função é talvez destinada a ser uma IIFE (Expressão de Função Invocada Imediatamente), que é uma função que é executada assim que é definida. Serão precisos mais alguns parêntises neste caso:

+ +
(function () {
+
+})();
+ +

Funções com nome

+ +

Se você está a usar uma função com identificador, ainda precisará fornecer um nome de função após a palavra-chave da função. O código seguinte não funciona:

+ +
function Greeter() {
+  german: function () {
+    return "Moin";
+  }
+}
+// SyntaxError: function statement requires a name
+
+ +

O código seguinte irá funcionar por exemplo:

+ +
function Greeter() {
+  german: function g() {
+    return "Moin";
+  }
+}
+ +

Métodos de objectos

+ +

Se você pretendia criar um método de um objeto, você precisará criar um objeto. A sintaxe a seguir sem um nome após a palavra-chave function é válida.

+ +
var greeter = {
+  german: function () {
+    return "Moin";
+  }
+};
+ +

Sintaxe de Callback

+ +

Além disso, verifique a sintaxe ao usar callbacks. Parêntisis e virgurlas podem facilmente se tornar complicados.

+ +
promise.then(
+  function() {
+    console.log("success");
+  });
+  function() {
+    console.log("error");
+}
+// SyntaxError: function statement requires a name
+
+ +

:

+ +
promise.then(
+  function() {
+    console.log("success");
+  },
+  function() {
+    console.log("error");
+  }
+);
+
+ +

Veja também

+ + diff --git "a/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/bloco/index.html" "b/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/bloco/index.html" deleted file mode 100644 index a3104dbeae..0000000000 --- "a/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/bloco/index.html" +++ /dev/null @@ -1,116 +0,0 @@ ---- -title: Bloco (block) -slug: Web/JavaScript/Reference/Extratos_e_declarações/bloco -tags: - - Declaração - - Funcionalidade de Linguagem - - JavaScript - - Referencia -translation_of: Web/JavaScript/Reference/Statements/block ---- -
Bloco {{jsSidebar("Statements")}}
- -

Uma declaralção bloco (ou declaração composto em outras linguagens) é utilizada para agrupar zero ou mais declarações. O bloco é delimitado por um par de chavetas (“chavetas { }”) e opcionalmente poderá ser {{jsxref("Statements/label", "labelled", "", 1)}}:

- -
{{EmbedInteractiveExample("pages/js/statement-block.html", "taller")}}
- - - -

Sintaxe

- -

Declaração de Bloco

- -
{
-  StatementList
-}
-
- -

Declaração de Bloco Etiquetado

- -
LabelIdentifier: {
-  StatementList
-}
-
- -
-
StatementList
-
Statements grouped within the block statement.
-
LabelIdentifier
-
An optional {{jsxref("Statements/label", "label", "", 1)}} for visual identification or as a target for {{jsxref("Statements/break", "break")}}.
-
- -

Descrição

- -

The block statement is often called compound statement in other languages. It allows you to use multiple statements where JavaScript expects only one statement. Combining statements into blocks is a common practice in JavaScript. The opposite behavior is possible using an empty statement, where you provide no statement, although one is required.

- -

Blocks are commonly used in association with {{jsxref("Statements/if...else", "if...else")}} and {{jsxref("Statements/for", "for")}} statements.

- -

Block Scoping Rules

- -

With var or function declaration in non-strict mode

- -

Variables declared with var or created by function declarations in non-strict mode do not have block scope. Variables introduced within a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. In other words, block statements do not introduce a scope. For example:

- -
var x = 1;
-{
-  var x = 2;
-}
-console.log(x); // logs 2
-
- -

This logs 2 because the var x statement within the block is in the same scope as the var x statement before the block.

- -

In non-strict code, function declarations inside blocks behave strangely. Do not use them.

- -

With let, const or function declaration in strict mode

- -

By contrast, identifiers declared with {{jsxref("Statements/let", "let")}} and {{jsxref("Statements/const", "const")}} do have block scope:

- -
let x = 1;
-{
-  let x = 2;
-}
-console.log(x); // logs 1
- -

The x = 2 is limited in scope to the block in which it was defined.

- -

The same is true of const:

- -
const c = 1;
-{
-  const c = 2;
-}
-console.log(c); // logs 1 and does not throw SyntaxError...
- -

Note that the block-scoped const c = 2 does not throw a SyntaxError: Identifier 'c' has already been declared because it can be declared uniquely within the block.

- -

In strict mode, starting with ES2015, functions inside blocks are scoped to that block. Prior to ES2015, block-level functions were forbidden in strict mode.

- -

Especificações

- - - - - - - - - - - - -
Especificação
{{SpecName('ESDraft', '#sec-block', 'Block statement')}}
- -

Compatibilidade de navegador

- - - -

{{Compat("javascript.statements.block")}}

- -

Consulte também

- - diff --git "a/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/for/index.html" "b/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/for/index.html" deleted file mode 100644 index ac7586e98b..0000000000 --- "a/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/for/index.html" +++ /dev/null @@ -1,145 +0,0 @@ ---- -title: for -slug: Web/JavaScript/Reference/Extratos_e_declarações/for -tags: - - Declaração - - Funcionalidade de Linguagem - - JavaScript - - Loop - - Referencia - - Repetição - - for -translation_of: Web/JavaScript/Reference/Statements/for ---- -
{{jsSidebar("Statements")}}
- -

A declaração "for" cria uma repetição (loop) que consiste de três expressões opcionais, entre parênteses e separados por ponto e vírgula, seguido de uma declaração (normalmente bdeclaraçãod e bloco (block)) para ser executada na repetição.

- -
{{EmbedInteractiveExample("pages/js/statement-for.html")}}
- - - -

Sintaxe

- -
for ([initialization]; [condition]; [final-expression])
-   statement
- -
-
initialization
-
An expression (including assignment expressions) or variable declaration evaluated once before the loop begins. Typically used to initialize a counter variable. This expression may optionally declare new variables with var or let keywords. Variables declared with var are not local to the loop, i.e. they are in the same scope the for loop is in. Variables declared with let are local to the statement.
-
The result of this expression is discarded.
-
condition
-
An expression to be evaluated before each loop iteration. If this expression evaluates to true, statement is executed. This conditional test is optional. If omitted, the condition always evaluates to true. If the expression evaluates to false, execution skips to the first expression following the for construct.
-
final-expression
-
An expression to be evaluated at the end of each loop iteration. This occurs before the next evaluation of condition. Generally used to update or increment the counter variable.
-
statement
-
A statement that is executed as long as the condition evaluates to true. To execute multiple statements within the loop, use a {{jsxref("Statements/block", "block", "", 0)}} statement ({ ... }) to group those statements. To execute no statement within the loop, use an {{jsxref("Statements/empty", "empty", "", 0)}} statement (;).
-
- -

Exemplos

- -

Using for

- -

The following for statement starts by declaring the variable i and initializing it to 0. It checks that i is less than nine, performs the two succeeding statements, and increments i by 1 after each pass through the loop.

- -
for (let i = 0; i < 9; i++) {
-   console.log(i);
-   // more statements
-}
-
- -

Optional for expressions

- -

All three expressions in the head of the for loop are optional.

- -

For example, in the initialization block it is not required to initialize variables:

- -
var i = 0;
-for (; i < 9; i++) {
-    console.log(i);
-    // more statements
-}
-
- -

Like the initialization block, the condition block is also optional. If you are omitting this expression, you must make sure to break the loop in the body in order to not create an infinite loop.

- -
for (let i = 0;; i++) {
-   console.log(i);
-   if (i > 3) break;
-   // more statements
-}
- -

You can also omit all three blocks. Again, make sure to use a {{jsxref("Statements/break", "break")}} statement to end the loop and also modify (increase) a variable, so that the condition for the break statement is true at some point.

- -
var i = 0;
-
-for (;;) {
-  if (i > 3) break;
-  console.log(i);
-  i++;
-}
-
- -

Using for without a statement

- -

The following for cycle calculates the offset position of a node in the final-expression section, and therefore it does not require the use of a statement section, a semicolon is used instead.

- -
function showOffsetPos(sId) {
-
-  var nLeft = 0, nTop = 0;
-
-  for (
-
-    var oItNode = document.getElementById(sId); /* initialization */
-
-    oItNode; /* condition */
-
-    nLeft += oItNode.offsetLeft, nTop += oItNode.offsetTop, oItNode = oItNode.offsetParent /* final-expression */
-
-  ); /* semicolon */
-
-  console.log('Offset position of \'' + sId + '\' element:\n left: ' + nLeft + 'px;\n top: ' + nTop + 'px;');
-
-}
-
-/* Example call: */
-
-showOffsetPos('content');
-
-// Output:
-// "Offset position of "content" element:
-// left: 0px;
-// top: 153px;"
- -
Note: This is one of the few cases in JavaScript where the semicolon is mandatory. Indeed, without the semicolon the line that follows the cycle declaration will be considered a statement.
- -

Especificações

- - - - - - - - - - -
Especificação
{{SpecName('ESDraft', '#sec-for-statement', 'for statement')}}
- -

Compatibilidade de navegador

- - - -

{{Compat("javascript.statements.for")}}

- -

Consulte também

- - diff --git "a/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/index.html" "b/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/index.html" deleted file mode 100644 index af841906a1..0000000000 --- "a/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/index.html" +++ /dev/null @@ -1,150 +0,0 @@ ---- -title: Declarações e instruções -slug: Web/JavaScript/Reference/Extratos_e_declarações -tags: - - JavaScript - - Referencia - - declarações - - instruções -translation_of: Web/JavaScript/Reference/Statements ---- -
{{jsSidebar("Statements")}}
- -

JavaScript applications consist of statements with an appropriate syntax. A single statement may span multiple lines. Multiple statements may occur on a single line if each statement is separated by a semicolon. This isn't a keyword, but a group of keywords.

- -

Declarações e instruções por categoria

- -

For an alphabetical listing see the sidebar on the left.

- -

Controlo de Fluxo

- -
-
{{jsxref("Statements/block", "Block")}}
-
A block statement is used to group zero or more statements. The block is delimited by a pair of curly brackets.
-
{{jsxref("Statements/break", "break")}}
-
Terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement.
-
{{jsxref("Statements/continue", "continue")}}
-
Terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.
-
{{jsxref("Statements/Empty", "Empty")}}
-
An empty statement is used to provide no statement, although the JavaScript syntax would expect one.
-
{{jsxref("Statements/if...else", "if...else")}}
-
Executes a statement if a specified condition is true. If the condition is false, another statement can be executed.
-
{{jsxref("Statements/switch", "switch")}}
-
Evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case.
-
{{jsxref("Statements/throw", "throw")}}
-
Throws a user-defined exception.
-
{{jsxref("Statements/try...catch", "try...catch")}}
-
Marks a block of statements to try, and specifies a response, should an exception be thrown.
-
- -

Declarações

- -
-
{{jsxref("Statements/var", "var")}}
-
Declares a variable, optionally initializing it to a value.
-
{{jsxref("Statements/let", "let")}}
-
Declares a block scope local variable, optionally initializing it to a value.
-
{{jsxref("Statements/const", "const")}}
-
Declares a read-only named constant.
-
- -

Funções e classes

- -
-
{{jsxref("Statements/function", "function")}}
-
Declara as funções com parâmetros especificados.
-
{{jsxref("Statements/function*", "function*")}}
-
Generators functions enable writing iterators more easily.
-
{{jsxref("Statements/async_function", "async function")}}
-
Declares an async function with the specified parameters.
-
{{jsxref("Statements/return", "return")}}
-
Specifies the value to be returned by a function.
-
{{jsxref("Statements/class", "class")}}
-
Declara uma Classe.
-
- -

Iterações

- -
-
{{jsxref("Statements/do...while", "do...while")}}
-
Creates a loop that executes a specified statement until the test condition evaluates to false. The condition is evaluated after executing the statement, resulting in the specified statement executing at least once.
-
{{jsxref("Statements/for", "for")}}
-
Creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.
-
{{deprecated_inline}} {{non-standard_inline()}} {{jsxref("Statements/for_each...in", "for each...in")}}
-
Iterates a specified variable over all values of object's properties. For each distinct property, a specified statement is executed.
-
{{jsxref("Statements/for...in", "for...in")}}
-
Iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.
-
{{jsxref("Statements/for...of", "for...of")}}
-
Iterates over iterable objects (including {{jsxref("Global_Objects/Array","arrays","","true")}}, array-like objects, iterators and generators), invoking a custom iteration hook with statements to be executed for the value of each distinct property.
-
{{jsxref("Statements/while", "while")}}
-
Creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement.
-
- -

Outros

- -
-
{{jsxref("Statements/debugger", "debugger")}}
-
Invokes any available debugging functionality. If no debugging functionality is available, this statement has no effect.
-
{{jsxref("Statements/export", "export")}}
-
Used to export functions to make them available for imports in external modules, another scripts.
-
{{jsxref("Statements/import", "import")}}
-
Used to import functions exported from an external module, another script.
-
import.meta
-
A meta-property exposing context-specific metadata to a JavaScript module.
-
{{jsxref("Statements/label", "label")}}
-
Provides a statement with an identifier that you can refer to using a break or continue statement.
-
- -
-
{{deprecated_inline}} {{jsxref("Statements/with", "with")}}
-
Extends the scope chain for a statement.
-
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('ES1', '#sec-12', 'Statements')}}{{Spec2('ES1')}}Initial definition
{{SpecName('ES3', '#sec-12', 'Statements')}}{{Spec2('ES3')}} 
{{SpecName('ES5.1', '#sec-12', 'Statements')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}{{Spec2('ES6')}}New: function*, let, for...of, yield, class
{{SpecName('ESDraft', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}{{Spec2('ESDraft')}} 
- -

Compatibilidade de navegador

- - - -

{{Compat("javascript.statements")}}

- -

Consultar também

- - diff --git "a/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/return/index.html" "b/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/return/index.html" deleted file mode 100644 index 6cec134992..0000000000 --- "a/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/return/index.html" +++ /dev/null @@ -1,148 +0,0 @@ ---- -title: return -slug: Web/JavaScript/Reference/Extratos_e_declarações/return -tags: - - Declaração - - JavaScript -translation_of: Web/JavaScript/Reference/Statements/return ---- -
{{jsSidebar("Statements")}}
- -

The return statement ends function execution and specifies a value to be returned to the function caller.

- -

Sintaxe

- -
return [[expression]]; 
- -
-
expression
-
The expression whose value is to be returned. If omitted, undefined is returned instead.
-
- -

Descrição

- -

When a return statement is used in a function body, the execution of the function is stopped. If specified, a given value is returned to the function caller. For example, the following function returns the square of its argument, x, where x is a number.

- -
function square(x) {
-   return x * x;
-}
-var demo = square(3);
-// demo will equal 9
-
- -

If the value is omitted, undefined is returned instead.

- -

The following return statements all break the function execution:

- -
return;
-return true;
-return false;
-return x;
-return x + y / 3;
-
- -

Inserção Automática de Ponto e Vírgula

- -

The return statement is affected by automatic semicolon insertion (ASI). No line terminator is allowed between the return keyword and the expression.

- -
return
-a + b;
-
- -

is transformed by ASI into:

- -
return;
-a + b;
-
- -

The console will warn "unreachable code after return statement".

- -
Starting with Gecko 40 {{geckoRelease(40)}}, a warning is shown in the console if unreachable code is found after a return statement.
- -

Exemplos

- -

Interromper uma função

- -

A function immediately stops at the point where return is called.

- -
function counter() {
-  for (var count = 1; ; count++) {  // infinite loop
-    console.log(count + 'A'); // until 5
-      if (count === 5) {
-        return;
-      }
-      console.log(count + 'B');  // until 4
-    }
-  console.log(count + 'C');  // never appears
-}
-
-counter();
-
-// Output:
-// 1A
-// 1B
-// 2A
-// 2B
-// 3A
-// 3B
-// 4A
-// 4B
-// 5A
-
- -

Devolver uma função

- -

See also the article about Closures.

- -
function magic(x) {
-  return function calc(x) { return x * 42; };
-}
-
-var answer = magic();
-answer(1337); // 56154
-
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-12.9', 'Return statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-return-statement', 'Return statement')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-return-statement', 'Return statement')}}{{Spec2('ESDraft')}} 
- -

Compatibilidade de navegador

- - - -

{{Compat("javascript.statements.return")}}

- -

Consulte também

- - diff --git "a/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/throw/index.html" "b/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/throw/index.html" deleted file mode 100644 index 9e7a8bf54e..0000000000 --- "a/files/pt-pt/web/javascript/reference/extratos_e_declara\303\247\303\265es/throw/index.html" +++ /dev/null @@ -1,271 +0,0 @@ ---- -title: throw -slug: Web/JavaScript/Reference/Extratos_e_declarações/throw -tags: - - Comando - - Declaração - - JavaScript -translation_of: Web/JavaScript/Reference/Statements/throw ---- -
{{jsSidebar("Statements")}}
- -

A declaração throw lança uma exeção definida pelo utilizador. A execução da função atual irá parar (os comandos depois de throw não serão executados), e o controle será passado para o primeiro bloco catch no conjunto de chamadas. Se não existir nenhum bloco catch entre as funções de caller, o programa irá terminar.

- -

Sintaxe

- -
expressão throw; 
- -
-
expressão
-
A expressão para throw.
-
- -

Descrição

- -

Use the throw statement to throw an exception. When you throw an exception, expression specifies the value of the exception. Each of the following throws an exception:

- -
throw 'Error2'; // generates an exception with a string value
-throw 42;       // generates an exception with the value 42
-throw true;     // generates an exception with the value true
- -

Also note that the throw statement is affected by automatic semicolon insertion (ASI) as no line terminator between the throw keyword and the expression is allowed.

- -

Exemplos

- -

Throw um objeto

- -

You can specify an object when you throw an exception. You can then reference the object's properties in the catch block. The following example creates an object of type UserException and uses it in a throw statement.

- -
function UserException(message) {
-   this.message = message;
-   this.name = 'UserException';
-}
-function getMonthName(mo) {
-   mo = mo - 1; // Adjust month number for array index (1 = Jan, 12 = Dec)
-   var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
-      'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
-   if (months[mo] !== undefined) {
-      return months[mo];
-   } else {
-      throw new UserException('InvalidMonthNo');
-   }
-}
-
-try {
-   // statements to try
-   var myMonth = 15; // 15 is out of bound to raise the exception
-   var monthName = getMonthName(myMonth);
-} catch (e) {
-   monthName = 'unknown';
-   console.log(e.message, e.name); // pass exception object to err handler
-}
-
- -

Outro exemplo de throwing um objeto

- -

The following example tests an input string for a U.S. zip code. If the zip code uses an invalid format, the throw statement throws an exception by creating an object of type ZipCodeFormatException.

- -
/*
- * Creates a ZipCode object.
- *
- * Accepted formats for a zip code are:
- *    12345
- *    12345-6789
- *    123456789
- *    12345 6789
- *
- * If the argument passed to the ZipCode constructor does not
- * conform to one of these patterns, an exception is thrown.
- */
-
-function ZipCode(zip) {
-   zip = new String(zip);
-   pattern = /[0-9]{5}([- ]?[0-9]{4})?/;
-   if (pattern.test(zip)) {
-      // zip code value will be the first match in the string
-      this.value = zip.match(pattern)[0];
-      this.valueOf = function() {
-         return this.value
-      };
-      this.toString = function() {
-         return String(this.value)
-      };
-   } else {
-      throw new ZipCodeFormatException(zip);
-   }
-}
-
-function ZipCodeFormatException(value) {
-   this.value = value;
-   this.message = 'does not conform to the expected format for a zip code';
-   this.toString = function() {
-      return this.value + this.message;
-   };
-}
-
-/*
- * This could be in a script that validates address data
- * for US addresses.
- */
-
-const ZIPCODE_INVALID = -1;
-const ZIPCODE_UNKNOWN_ERROR = -2;
-
-function verifyZipCode(z) {
-   try {
-      z = new ZipCode(z);
-   } catch (e) {
-      if (e instanceof ZipCodeFormatException) {
-         return ZIPCODE_INVALID;
-      } else {
-         return ZIPCODE_UNKNOWN_ERROR;
-      }
-   }
-   return z;
-}
-
-a = verifyZipCode(95060);         // returns 95060
-b = verifyZipCode(9560);          // returns -1
-c = verifyZipCode('a');           // returns -1
-d = verifyZipCode('95060');       // returns 95060
-e = verifyZipCode('95060 1234');  // returns 95060 1234
-
- -

Rethrow uma exceção

- -

You can use throw to rethrow an exception after you catch it. The following example catches an exception with a numeric value and rethrows it if the value is over 50. The rethrown exception propagates up to the enclosing function or to the top level so that the user sees it.

- -
try {
-   throw n; // throws an exception with a numeric value
-} catch (e) {
-   if (e <= 50) {
-      // statements to handle exceptions 1-50
-   } else {
-      // cannot handle this exception, so rethrow
-      throw e;
-   }
-}
-
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.4
{{SpecName('ES5.1', '#sec-12.13', 'throw statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-throw-statement', 'throw statement')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-throw-statement', 'throw statement')}}{{Spec2('ESDraft')}} 
- -

Compatibilidade de navegador

- - - -

{{Compat("javascript.statements.throw")}}

- -

Consulte também

- - - -
- - - - - -
diff --git a/files/pt-pt/web/javascript/reference/funcionalidades_obsoletas/index.html b/files/pt-pt/web/javascript/reference/funcionalidades_obsoletas/index.html deleted file mode 100644 index 9d0ae63c62..0000000000 --- a/files/pt-pt/web/javascript/reference/funcionalidades_obsoletas/index.html +++ /dev/null @@ -1,289 +0,0 @@ ---- -title: Funcionalidades obsoletas -slug: Web/JavaScript/Reference/Funcionalidades_obsoletas -tags: - - JavaScript - - Obsoleto -translation_of: Web/JavaScript/Reference/Deprecated_and_obsolete_features ---- -
{{JsSidebar("More")}}
- -

Esta página lista as funcionalidades de JavaScript que estão obsoletas (ou seja, ainda disponíveis, mas planeadas para remoção) e obsoletas (isto é, não são mais utilizáveis).

- -

Funcionalidades obsoletas

- -

Estas funcionalidades obsoletas ainda podem ser utilziadas, mas devem ser utilizadas ​​com cuidado, pois espera-se que estas sejam removidas inteiramente no futuro. Deverá trabalhar para remover a utilização das mesmas do seu código..

- -

Propriedades de RegExp

- -

The following properties are deprecated. This does not affect their use in {{jsxref("String.replace", "replacement strings", "", 1)}}:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropriedadesDescrição
{{jsxref("RegExp.n", "$1-$9")}} -

Parenthesized substring matches, if any.
- Warning: Using these properties can result in problems, since browser extensions can modify them. Avoid them!

-
{{jsxref("RegExp.input", "$_")}}See input.
{{jsxref("RegExp.multiline", "$*")}}See multiline.
{{jsxref("RegExp.lastMatch", "$&")}}See lastMatch.
{{jsxref("RegExp.lastParen", "$+")}}See lastParen.
{{jsxref("RegExp.leftContext", "$`")}}See leftContext.
{{jsxref("RegExp.rightContext", "$'")}}See rightContext.
{{jsxref("RegExp.input", "input")}}The string against which a regular expression is matched.
{{jsxref("RegExp.lastMatch", "lastMatch")}}The last matched characters.
{{jsxref("RegExp.lastParen", "lastParen")}}The last parenthesized substring match, if any.
{{jsxref("RegExp.leftContext", "leftContext")}}The substring preceding the most recent match.
{{jsxref("RegExp.rightContext", "rightContext")}}The substring following the most recent match.
- -

The following are now properties of RegExp instances, no longer of the RegExp object:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropriedadesDescrição
{{jsxref("RegExp.global", "global")}}Whether or not to test the regular expression against all possible matches in a string, or only against the first.
{{jsxref("RegExp.ignoreCase", "ignoreCase")}}Whether or not to ignore case while attempting a match in a string.
{{jsxref("RegExp.lastIndex", "lastIndex")}}The index at which to start the next match.
{{jsxref("RegExp.multiline", "multiline")}}Whether or not to search in strings across multiple lines.
{{jsxref("RegExp.source", "source")}}The text of the pattern.
- -

Métodos de egExp

- - - -

Propriedades de Function

- - - -

Gerador de Legacy

- - - -

Iterator

- - - -

Métodos de Object

- - - -

Métodos de Date

- - - -

Functions

- - - -

Proxy

- - - -

Sequências de Escape

- - - -

Métodos de String

- - - -

Funcionalidades removidas

- -

Estas funcionalidades obsoletas foram totalmente removidas do JavaScript e não podem mais ser utilizadas a partir da versão indicada do JavaScript.

- -

Object

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PropertyDescription
{{jsxref("Global_Objects/Object/count", "__count__")}}Returns the number of enumerable properties directly on a user-defined object.
{{jsxref("Global_Objects/Object/Parent", "__parent__")}}Points to an object's context.
{{jsxref("Global_Objects/Object/eval", "Object.prototype.eval()")}}Evaluates a string of JavaScript code in the context of the specified object.
{{jsxref("Object.observe()")}}Asynchronously observing the changes to an object.
{{jsxref("Object.unobserve()")}}Remove observers.
{{jsxref("Object.getNotifier()")}}Creates an object that allows to synthetically trigger a change.
- -

Function

- - - - - - - - - - - - -
PropertyDescription
{{jsxref("Global_Objects/Function/arity", "arity")}}Number of formal arguments.
- -

Array

- - - - - - - - - - - - - - - - -
PropertyDescription
{{jsxref("Array.observe()")}}Asynchronously observing changes to Arrays.
{{jsxref("Array.unobserve()")}}Remove observers.
- -

Number

- - - -

ParallelArray

- - - -

Statements

- - - -

E4X

- -

See E4X for more information.

- -

Variáveis Sharp

- -

Consulte Sharp variables in JavaScript para mais informação.

diff --git a/files/pt-pt/web/javascript/reference/funcoes/arguments/index.html b/files/pt-pt/web/javascript/reference/funcoes/arguments/index.html deleted file mode 100644 index c7ac84a4b9..0000000000 --- a/files/pt-pt/web/javascript/reference/funcoes/arguments/index.html +++ /dev/null @@ -1,228 +0,0 @@ ---- -title: O objeto arguments -slug: Web/JavaScript/Reference/Funcoes/arguments -tags: - - Class - - Funções - - JavaScript - - Referencia - - arguments -translation_of: Web/JavaScript/Reference/Functions/arguments ---- -

{{JSSidebar("Functions")}}

- -

arguments é um objeto semelhante a uma "Matiz" acessível dentro de functions que contém os valores dos argumentos passados ​​para essa função.

- -
-

Nota: If you're writing ES6 compatible code, then rest parameters should be preferred.

-
- -
-

Nota: “Array-like” means that arguments has a length property and properties indexed from zero, but it doesn't have {{JSxRef("Array")}}'s built-in methods like forEach and map. See §Description for details.

-
- -
{{EmbedInteractiveExample("pages/js/functions-arguments.html")}}
- - - -

Sintaxe

- -
arguments
- -

Descrição

- -

The arguments object is a local variable available within all non-arrow functions. You can refer to a function's arguments inside that function by using its arguments object. It has entries for each argument the function was called with, with the first entry's index at 0.

- -

For example, if a function is passed 3 arguments, you can access them as follows:

- -
arguments[0] // first argument
-arguments[1] // second argument
-arguments[2] // third argument
-
- -

Each argument can also be set or reassigned:

- -
arguments[1] = 'new value';
-
- -

The arguments object is not an {{JSxRef("Array")}}. It is similar, but does not have any Array properties except length. For example, it does not have the pop method. However, it can be converted to a real Array:

- -
var args = Array.prototype.slice.call(arguments);
-// Using an array literal is shorter than above but allocates an empty array
-var args = [].slice.call(arguments);
-
- -

As you can do with any Array-like object, you can use ES2015's {{JSxRef("Array.from()")}} method or spread operator to convert arguments to a real Array:

- -
let args = Array.from(arguments);
-// or
-let args = [...arguments];
- -

The arguments object is useful for functions called with more arguments than they are formally declared to accept. This technique is useful for functions that can be passed a variable number of arguments, such as Math.min(). This example function accepts any number of string arguments and returns the longest one:

- -
function longestString() {
-  var longest = '';
-  for (var i=0; i < arguments.length; i++) {
-    if (arguments[i].length > longest.length) {
-      longest = arguments[i];
-    }
-  }
-  return longest;
-}
-
- -

You can use arguments.length to count how many arguments the function was called with. If you instead want to count how many parameters a function is declared to accept, inspect that function's length property.

- -

Utilizar typeof com Arguments

- -

The typeof operator returns 'object' when used with arguments

- -
console.log(typeof arguments); // 'object' 
- -

The type of individual arguments can be determined by indexing arguments:

- -
console.log(typeof arguments[0]); // returns the type of the first argument
- -

Propriedades

- -
-
-
{{jsxref("Functions/arguments/callee", "arguments.callee")}}
-
Reference to the currently executing function that the arguments belong to.
-
{{jsxref("Functions/arguments/length", "arguments.length")}}
-
The number of arguments that were passed to the function.
-
{{jsxref("Functions/arguments/@@iterator", "arguments[@@iterator]")}}
-
Returns a new {{jsxref("Array/@@iterator", "Array iterator", "", 0)}} object that contains the values for each index in arguments.
-
- -

Exemplos

- -

Definir uma function que concatena várias strings

- -

This example defines a function that concatenates several strings. The function's only formal argument is a string containing the characters that separate the items to concatenate.

- -
function myConcat(separator) {
-  var args = Array.prototype.slice.call(arguments, 1);
-  return args.join(separator);
-}
- -

You can pass as many arguments as you like to this function. It returns a string list using each argument in the list:

- -
// returns "red, orange, blue"
-myConcat(', ', 'red', 'orange', 'blue');
-
-// returns "elephant; giraffe; lion; cheetah"
-myConcat('; ', 'elephant', 'giraffe', 'lion', 'cheetah');
-
-// returns "sage. basil. oregano. pepper. parsley"
-myConcat('. ', 'sage', 'basil', 'oregano', 'pepper', 'parsley');
- -

Definir uma function que cria listas HTML

- -

This example defines a function that creates a string containing HTML for a list. The only formal argument for the function is a string that is "u" if the list is to be unordered (bulleted), or "o" if the list is to be ordered (numbered). The function is defined as follows:

- -
function list(type) {
-  var html = '<' + type + 'l><li>';
-  var args = Array.prototype.slice.call(arguments, 1);
-  html += args.join('</li><li>');
-  html += '</li></' + type + 'l>'; // end list
-
-  return html;
-}
- -

You can pass any number of arguments to this function, and it adds each argument as a list item to a list of the type indicated. For example:

- -
var listHTML = list('u', 'One', 'Two', 'Three');
-
-/* listHTML is:
-"<ul><li>One</li><li>Two</li><li>Three</li></ul>"
-*/
- -

Parâmetros Rest, predefinição, e desestruturados

- -

The arguments object can be used in conjunction with rest, default, and destructured parameters.

- -
function foo(...args) {
-  return args;
-}
-foo(1, 2, 3); // [1,2,3]
-
- -

While the presence of rest, default, or destructured parameters does not alter the behavior of the arguments object in strict mode code, there is a subtle difference for non-strict code.

- -

In strict-mode code, the arguments object behaves the same whether or not a function is passed rest, default, or destructured parameters. That is, assigning new values to variables in the body of the function will not affect the arguments object. Nor will assigning new variables to the arguments object affect the value of variables.

- -
-

Nota: You cannot write a "use strict"; directive in the body of a function definition that accepts rest, default, or destructured parameters. Doing so will throw a syntax error.

-
- -

Non-strict functions that are passed only simple parameters (that is, not rest, default, or restructured parameters) will sync the value of variables new values in the body of the function with the arguments object, and vice versa:

- -
function func(a) {
-  arguments[0] = 99; // updating arguments[0] also updates a
-  console.log(a);
-}
-func(10); // 99
-
- -

And also:

- -
function func(a) {
-  a = 99; // updating a also updates arguments[0]
-  console.log(arguments[0]);
-}
-func(10); // 99
-
- -

Conversely, non-strict functions that are passed rest, default, or destructured parameters will not sync new values assigned to argument variables in the function body with the arguments object. Instead, the arguments object in non-strict functions with complex parameters will always reflect the values passed to the function when the function was called (this is the same behavior as exhibited by all strict-mode functions, regardless of the type of variables they are passed):

- -
function func(a = 55) {
-  arguments[0] = 99; // updating arguments[0] does not also update a
-  console.log(a);
-}
-func(10); // 10
- -

E também:

- -
function func(a = 55) {
-  a = 99; // updating a does not also update arguments[0]
-  console.log(arguments[0]);
-}
-func(10); // 10
-
- -

E também:

- -
// An untracked default parameter
-function func(a = 55) {
-  console.log(arguments[0]);
-}
-func(); // undefined
- -

Especificações

- - - - - - - - - - - - -
Especificação
{{SpecName('ESDraft', '#sec-arguments-exotic-objects', 'Arguments Exotic Objects')}}
- -

Compatibildiade de navegador

- - - -

{{Compat("javascript.functions.arguments")}}

- -

Consulte também

- - diff --git a/files/pt-pt/web/javascript/reference/funcoes/funcoes_seta/index.html b/files/pt-pt/web/javascript/reference/funcoes/funcoes_seta/index.html deleted file mode 100644 index aa7b7b3121..0000000000 --- a/files/pt-pt/web/javascript/reference/funcoes/funcoes_seta/index.html +++ /dev/null @@ -1,399 +0,0 @@ ---- -title: Expressões da função "Seta" -slug: Web/JavaScript/Reference/Funcoes/Funcoes_seta -translation_of: Web/JavaScript/Reference/Functions/Arrow_functions ---- -
{{jsSidebar("Functions")}}
- -

Uma expressão da função seta é uma alternativa sintaticamente compacta a uma expressão de expressão de função regular, embora sem as suas próprias associações às palavras-chave this, arguments, super, ou new.target. As expressões de função (function) de seta são inadequadas como métodos, e não podem ser utilziadas como construtores.

- -
{{EmbedInteractiveExample("pages/js/functions-arrow.html")}}
- -

Sintaxe

- -

Basic syntax

- -
(param1, param2, …, paramN) => { statements }
-(param1, param2, …, paramN) => expression
-// equivalent to: => { return expression; }
-
-// Parentheses are optional when there's only one parameter name:
-(singleParam) => { statements }
-singleParam => { statements }
-
-// The parameter list for a function with no parameters should be written with a pair of parentheses.
-() => { statements }
-
- -

Advanced syntax

- -
// Parenthesize the body of a function to return an object literal expression:
-params => ({foo: bar})
-
-// Rest parameters and default parameters are supported
-(param1, param2, ...rest) => { statements }
-(param1 = defaultValue1, param2, …, paramN = defaultValueN) => {
-statements }
-
-// Destructuring within the parameter list is also supported
-var f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c;
-f(); // 6
-
- -

Descrição

- -

See also "ES6 In Depth: Arrow functions" on hacks.mozilla.org.

- -

Two factors influenced the introduction of arrow functions: the need for shorter functions and the behavior of the this keyword.

- -

Funções curtas

- -
var elements = [
-  'Hydrogen',
-  'Helium',
-  'Lithium',
-  'Beryllium'
-];
-
-// This statement returns the array: [8, 6, 7, 9]
-elements.map(function(element) {
-  return element.length;
-});
-
-// The regular function above can be written as the arrow function below
-elements.map((element) => {
-  return element.length;
-}); // [8, 6, 7, 9]
-
-// When there is only one parameter, we can remove the surrounding parentheses
-elements.map(element => {
-  return element.length;
-}); // [8, 6, 7, 9]
-
-// When the only statement in an arrow function is `return`, we can remove `return` and remove
-// the surrounding curly brackets
-elements.map(element => element.length); // [8, 6, 7, 9]
-
-// In this case, because we only need the length property, we can use destructuring parameter:
-// Notice that the `length` corresponds to the property we want to get whereas the
-// obviously non-special `lengthFooBArX` is just the name of a variable which can be changed
-// to any valid variable name you want
-elements.map(({ length: lengthFooBArX }) => lengthFooBArX); // [8, 6, 7, 9]
-
-// This destructuring parameter assignment can also be written as seen below. However, note that in
-// this example we are not assigning `length` value to the made up property. Instead, the literal name
-// itself of the variable `length` is used as the property we want to retrieve from the object.
-elements.map(({ length }) => length); // [8, 6, 7, 9]
-
- -

No separate this

- -

Before arrow functions, every new function defined its own this value based on how the function was called:

- - - -

This proved to be less than ideal with an object-oriented style of programming.

- -
function Person() {
-  // The Person() constructor defines `this` as an instance of itself.
-  this.age = 0;
-
-  setInterval(function growUp() {
-    // In non-strict mode, the growUp() function defines `this`
-    // as the global object (because it's where growUp() is executed.),
-    // which is different from the `this`
-    // defined by the Person() constructor.
-    this.age++;
-  }, 1000);
-}
-
-var p = new Person();
- -

In ECMAScript 3/5, the this issue was fixable by assigning the value in this to a variable that could be closed over.

- -
function Person() {
-  var that = this;
-  that.age = 0;
-
-  setInterval(function growUp() {
-    // The callback refers to the `that` variable of which
-    // the value is the expected object.
-    that.age++;
-  }, 1000);
-}
- -

Alternatively, a bound function could be created so that a preassigned this value would be passed to the bound target function (the growUp() function in the example above).

- -

An arrow function does not have its own this. The this value of the enclosing lexical scope is used; arrow functions follow the normal variable lookup rules. So while searching for this which is not present in current scope, an arrow function ends up finding the this from its enclosing scope.

- -

Thus, in the following code, the this within the function that is passed to setInterval has the same value as the this in the lexically enclosing function:

- -
function Person(){
-  this.age = 0;
-
-  setInterval(() => {
-    this.age++; // |this| properly refers to the Person object
-  }, 1000);
-}
-
-var p = new Person();
- -

Relation with strict mode

- -

Given that this comes from the surrounding lexical context, strict mode rules with regard to this are ignored.

- -
var f = () => { 'use strict'; return this; };
-f() === window; // or the global object
- -

All other strict mode rules apply normally.

- -

Invoked through call or apply

- -

Since arrow functions do not have their own this, the methods call() and apply() can only pass in parameters. Any this argument is ignored.

- -
var adder = {
-  base: 1,
-
-  add: function(a) {
-    var f = v => v + this.base;
-    return f(a);
-  },
-
-  addThruCall: function(a) {
-    var f = v => v + this.base;
-    var b = {
-      base: 2
-    };
-
-    return f.call(b, a);
-  }
-};
-
-console.log(adder.add(1));         // This would log 2
-console.log(adder.addThruCall(1)); // This would log 2 still
- -

No binding of arguments

- -

Arrow functions do not have their own arguments object. Thus, in this example, arguments is simply a reference to the arguments of the enclosing scope:

- -
var arguments = [1, 2, 3];
-var arr = () => arguments[0];
-
-arr(); // 1
-
-function foo(n) {
-  var f = () => arguments[0] + n; // foo's implicit arguments binding. arguments[0] is n
-  return f();
-}
-
-foo(3); // 6
- -

In most cases, using rest parameters is a good alternative to using an arguments object.

- -
function foo(n) {
-  var f = (...args) => args[0] + n;
-  return f(10);
-}
-
-foo(1); // 11
- -

Arrow functions used as methods

- -

As stated previously, arrow function expressions are best suited for non-method functions. Let's see what happens when we try to use them as methods:

- -
'use strict';
-
-var obj = { // does not create a new scope
-  i: 10,
-  b: () => console.log(this.i, this),
-  c: function() {
-    console.log(this.i, this);
-  }
-}
-
-obj.b(); // prints undefined, Window {...} (or the global object)
-obj.c(); // prints 10, Object {...}
- -

Arrow functions do not have their own this. Another example involving {{jsxref("Object.defineProperty()")}}:

- -
'use strict';
-
-var obj = {
-  a: 10
-};
-
-Object.defineProperty(obj, 'b', {
-  get: () => {
-    console.log(this.a, typeof this.a, this); // undefined 'undefined' Window {...} (or the global object)
-    return this.a + 10; // represents global object 'Window', therefore 'this.a' returns 'undefined'
-  }
-});
-
- -

Use of the new operator

- -

Arrow functions cannot be used as constructors and will throw an error when used with new.

- -
var Foo = () => {};
-var foo = new Foo(); // TypeError: Foo is not a constructor
- -

Use of prototype property

- -

Arrow functions do not have a prototype property.

- -
var Foo = () => {};
-console.log(Foo.prototype); // undefined
-
- -

Use of the yield keyword

- -

The yield keyword may not be used in an arrow function's body (except when permitted within functions further nested within it). As a consequence, arrow functions cannot be used as generators.

- -

Function body

- -

Arrow functions can have either a "concise body" or the usual "block body".

- -

In a concise body, only an expression is specified, which becomes the implicit return value. In a block body, you must use an explicit return statement.

- -
var func = x => x * x;
-// concise body syntax, implied "return"
-
-var func = (x, y) => { return x + y; };
-// with block body, explicit "return" needed
-
- -

Returning object literals

- -

Keep in mind that returning object literals using the concise body syntax params => {object:literal} will not work as expected.

- -
var func = () => { foo: 1 };
-// Calling func() returns undefined!
-
-var func = () => { foo: function() {} };
-// SyntaxError: function statement requires a name
- -

This is because the code inside braces ({}) is parsed as a sequence of statements (i.e. foo is treated like a label, not a key in an object literal).

- -

You must wrap the object literal in parentheses:

- -
var func = () => ({ foo: 1 });
- -

Line breaks

- -

An arrow function cannot contain a line break between its parameters and its arrow.

- -
var func = (a, b, c)
-  => 1;
-// SyntaxError: expected expression, got '=>'
- -

However, this can be amended by putting the line break after the arrow or using parentheses/braces as seen below to ensure that the code stays pretty and fluffy. You can also put line breaks between arguments.

- -
var func = (a, b, c) =>
-  1;
-
-var func = (a, b, c) => (
-  1
-);
-
-var func = (a, b, c) => {
-  return 1
-};
-
-var func = (
-  a,
-  b,
-  c
-) => 1;
-
-// no SyntaxError thrown
- -

Parsing order

- -

Although the arrow in an arrow function is not an operator, arrow functions have special parsing rules that interact differently with operator precedence compared to regular functions.

- -
let callback;
-
-callback = callback || function() {}; // ok
-
-callback = callback || () => {};
-// SyntaxError: invalid arrow-function arguments
-
-callback = callback || (() => {});    // ok
-
- -

More examples

- -
// An empty arrow function returns undefined
-let empty = () => {};
-
-(() => 'foobar')();
-// Returns "foobar"
-// (this is an Immediately Invoked Function Expression)
-
-var simple = a => a > 15 ? 15 : a;
-simple(16); // 15
-simple(10); // 10
-
-let max = (a, b) => a > b ? a : b;
-
-// Easy array filtering, mapping, ...
-
-var arr = [5, 6, 13, 0, 1, 18, 23];
-
-var sum = arr.reduce((a, b) => a + b);
-// 66
-
-var even = arr.filter(v => v % 2 == 0);
-// [6, 0, 18]
-
-var double = arr.map(v => v * 2);
-// [10, 12, 26, 0, 2, 36, 46]
-
-// More concise promise chains
-promise.then(a => {
-  // ...
-}).then(b => {
-  // ...
-});
-
-// Parameterless arrow functions that are visually easier to parse
-setTimeout( () => {
-  console.log('I happen sooner');
-  setTimeout( () => {
-    // deeper code
-    console.log('I happen later');
-  }, 1);
-}, 1);
-
- -

Specifications

- - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-arrow-function-definitions', 'Arrow Function Definitions')}}
- -

Browser compatibility

- -
- - -

{{Compat("javascript.functions.arrow_functions")}}

-
- -

See also

- - diff --git a/files/pt-pt/web/javascript/reference/funcoes/index.html b/files/pt-pt/web/javascript/reference/funcoes/index.html deleted file mode 100644 index 02b35fc7bd..0000000000 --- a/files/pt-pt/web/javascript/reference/funcoes/index.html +++ /dev/null @@ -1,594 +0,0 @@ ---- -title: Funções -slug: Web/JavaScript/Reference/Funcoes -tags: - - Constructor - - Função - - Funções - - JavaScript - - Parâmetro - - parâmetros -translation_of: Web/JavaScript/Reference/Functions ---- -
{{jsSidebar("Functions")}}
- -

Generally speaking, a function is a "subprogram" that can be called by code external (or internal in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the function body. Values can be passed to a function, and the function will return a value.

- -

In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects.

- -

For more examples and explanations, see also the JavaScript guide about functions.

- -

Descrição

- -

Every function in JavaScript is a Function object. See {{jsxref("Function")}} for information on properties and methods of Function objects.

- -

To return a value other than the default, a function must have a return statement that specifies the value to return. A function without a return statement will return a default value. In the case of a constructor called with the new keyword, the default value is the value of its this parameter. For all other functions, the default return value is {{jsxref("undefined")}}.

- -

The parameters of a function call are the function's arguments. Arguments are passed to functions by value. If the function changes the value of an argument, this change is not reflected globally or in the calling function. However, object references are values, too, and they are special: if the function changes the referred object's properties, that change is visible outside the function, as shown in the following example:

- -
/* Declare the function 'myFunc' */
-function myFunc(theObject) {
-  theObject.brand = "Toyota";
-}
-
-/*
- * Declare variable 'mycar';
- * create and initialize a new Object;
- * assign reference to it to 'mycar'
- */
-var mycar = {
-  brand: "Honda",
-  model: "Accord",
-  year: 1998
-};
-
-/* Logs 'Honda' */
-console.log(mycar.brand);
-
-/* Pass object reference to the function */
-myFunc(mycar);
-
-/*
- * Logs 'Toyota' as the value of the 'brand' property
- * of the object, as changed to by the function.
- */
-console.log(mycar.brand);
-
- -

The this keyword does not refer to the currently executing function, so you must refer to Function objects by name, even within the function body.

- -

Definindo funções

- -

There are several ways to define functions:

- -

The function declaration (function statement)

- -

There is a special syntax for declaring functions (see function statement for details):

- -
function name([param[, param[, ... param]]]) {
-   statements
-}
-
- -
-
name
-
The function name.
-
- -
-
param
-
The name of an argument to be passed to the function. A function can have up to 255 arguments.
-
- -
-
statements
-
The statements comprising the body of the function.
-
- -

The function expression (function expression)

- -

A function expression is similar to and has the same syntax as a function declaration (see function expression for details). A function expression may be a part of a larger expression. One can define "named" function expressions (where the name of the expression might be used in the call stack for example) or "anonymous" function expressions. Function expressions are not hoisted onto the beginning of the scope, therefore they cannot be used before they appear in the code.

- -
function [name]([param[, param[, ... param]]]) {
-   statements
-}
-
- -
-
name
-
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
-
- -
-
param
-
The name of an argument to be passed to the function. A function can have up to 255 arguments.
-
statements
-
The statements comprising the body of the function.
-
- -

Here is an example of an anonymous function expression (the name is not used):

- -
var myFunction = function() {
-    statements
-}
- -

It is also possible to provide a name inside the definition in order to create a named function expression:

- -
var myFunction = function namedFunction(){
-    statements
-}
-
- -

One of the benefit of creating a named function expression is that in case we encounted an error, the stack trace will contain the name of the function, making it easier to find the origin of the error.

- -

As we can see, both examples do not start with the function keyword. Statements involving functions which do not start with function are function expressions.

- -

When functions are used only once, a common pattern is an IIFE (Immediately Invokable Function Expression).

- -
(function() {
-    statements
-})();
- -

IIFE are function expressions that are invoked as soon as the function is declared.

- -

The generator function declaration (function* statement)

- -

There is a special syntax for generator function declarations (see {{jsxref('Statements/function*', 'function* statement')}} for details):

- -
function* name([param[, param[, ... param]]]) {
-   statements
-}
-
- -
-
name
-
The function name.
-
- -
-
param
-
The name of an argument to be passed to the function. A function can have up to 255 arguments.
-
- -
-
statements
-
The statements comprising the body of the function.
-
- -

The generator function expression (function* expression)

- -

A generator function expression is similar to and has the same syntax as a generator function declaration (see {{jsxref('Operators/function*', 'function* expression')}} for details):

- -
function* [name]([param[, param[, ... param]]]) {
-   statements
-}
-
- -
-
name
-
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
-
- -
-
param
-
The name of an argument to be passed to the function. A function can have up to 255 arguments.
-
statements
-
The statements comprising the body of the function.
-
- -

The arrow function expression (=>)

- -

An arrow function expression has a shorter syntax and lexically binds its this value (see arrow functions for details):

- -
([param[, param]]) => {
-   statements
-}
-
-param => expression
-
- -
-
param
-
The name of an argument. Zero arguments need to be indicated with ().  For only one argument, the parentheses are not required. (like foo => 1)
-
statements or expression
-
Multiple statements need to be enclosed in brackets. A single expression requires no brackets. The expression is also the implicit return value of the function.
-
- -

The Function constructor

- -
-

Note: Using the Function constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.

-
- -

As all other objects, {{jsxref("Function")}} objects can be created using the new operator:

- -
new Function (arg1, arg2, ... argN, functionBody)
-
- -
-
arg1, arg2, ... argN
-
Zero or more names to be used by the function as formal parameters. Each must be a proper JavaScript identifier.
-
- -
-
functionBody
-
A string containing the JavaScript statements comprising the function body.
-
- -

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

- -

The GeneratorFunction constructor

- -
-

Note: GeneratorFunction is not a global object, but could be obtained from generator function instance (see {{jsxref("GeneratorFunction")}} for more detail).

-
- -
-

Note: Using the GeneratorFunction constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.

-
- -

As all other objects, {{jsxref("GeneratorFunction")}} objects can be created using the new operator:

- -
new GeneratorFunction (arg1, arg2, ... argN, functionBody)
-
- -
-
arg1, arg2, ... argN
-
Zero or more names to be used by the function as formal argument names. Each must be a string that conforms to the rules for a valid JavaScript identifier or a list of such strings separated with a comma; for example "x", "theValue", or "a,b".
-
- -
-
functionBody
-
A string containing the JavaScript statements comprising the function definition.
-
- -

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

- -

Parâmetros de função

- -

Parâmetros predefinidos

- -

Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed. For more details, see default parameters.

- -

Parâmetros Rest

- -

The rest parameter syntax allows to represent an indefinite number of arguments as an array. For more details, see rest parameters.

- -

O objeto arguments

- -

You can refer to a function's arguments within the function by using the arguments object. See arguments.

- - - -

Definindo funções de método

- -

Getter and setter functions

- -

You can define getters (accessor methods) and setters (mutator methods) on any standard built-in object or user-defined object that supports the addition of new properties. The syntax for defining getters and setters uses the object literal syntax.

- -
-
get
-
-

Binds an object property to a function that will be called when that property is looked up.

-
-
set
-
Binds an object property to a function to be called when there is an attempt to set that property.
-
- -

Method definition syntax

- -

Starting with ECMAScript 2015, you are able to define own methods in a shorter syntax, similar to the getters and setters. See method definitions for more information.

- -
var obj = {
-  foo() {},
-  bar() {}
-};
- -

Constructor vs. declaration vs. expression

- -

Compare the following:

- -

A function defined with the Function constructor assigned to the variable multiply:

- -
var multiply = new Function('x', 'y', 'return x * y');
- -

A function declaration of a function named multiply:

- -
function multiply(x, y) {
-   return x * y;
-} // there is no semicolon here
-
- -

A function expression of an anonymous function assigned to the variable multiply:

- -
var multiply = function(x, y) {
-   return x * y;
-};
-
- -

A function expression of a function named func_name assigned to the variable multiply:

- -
var multiply = function func_name(x, y) {
-   return x * y;
-};
-
- -

Differences

- -

All do approximately the same thing, with a few subtle differences:

- -

There is a distinction between the function name and the variable the function is assigned to. The function name cannot be changed, while the variable the function is assigned to can be reassigned. The function name can be used only within the function's body. Attempting to use it outside the function's body results in an error (or undefined if the function name was previously declared via a var statement). For example:

- -
var y = function x() {};
-alert(x); // throws an error
-
- -

The function name also appears when the function is serialized via Function's toString method.

- -

On the other hand, the variable the function is assigned to is limited only by its scope, which is guaranteed to include the scope in which the function is declared.

- -

As the 4th example shows, the function name can be different from the variable the function is assigned to. They have no relation to each other. A function declaration also creates a variable with the same name as the function name. Thus, unlike those defined by function expressions, functions defined by function declarations can be accessed by their name in the scope they were defined in:

- -

A function defined by 'new Function' does not have a function name. However, in the SpiderMonkey JavaScript engine, the serialized form of the function shows as if it has the name "anonymous". For example, alert(new Function()) outputs:

- -
function anonymous() {
-}
-
- -

Since the function actually does not have a name, anonymous is not a variable that can be accessed within the function. For example, the following would result in an error:

- -
var foo = new Function("alert(anonymous);");
-foo();
-
- -

Unlike functions defined by function expressions or by the Function constructor, a function defined by a function declaration can be used before the function declaration itself. For example:

- -
foo(); // alerts FOO!
-function foo() {
-   alert('FOO!');
-}
-
- -

A function defined by a function expression or by a function declaration inherits the current scope. That is, the function forms a closure. On the other hand, a function defined by a Function constructor does not inherit any scope other than the global scope (which all functions inherit).

- -
/*
- * Declare and initialize a variable 'p' (global)
- * and a function 'myFunc' (to change the scope) inside which
- * declare a varible with same name 'p' (current) and
- * define three functions using three different ways:-
- *     1. function declaration
- *     2. function expression
- *     3. function constructor
- * each of which will log 'p'
- */
-var p = 5;
-function myFunc() {
-    var p = 9;
-
-    function decl() {
-        console.log(p);
-    }
-    var expr = function() {
-        console.log(p);
-    };
-    var cons = new Function('\tconsole.log(p);');
-
-    decl();
-    expr();
-    cons();
-}
-myFunc();
-
-/*
- * Logs:-
- * 9  - for 'decl' by function declaration (current scope)
- * 9  - for 'expr' by function expression (current scope)
- * 5  - for 'cons' by Function constructor (global scope)
- */
-
- -

Functions defined by function expressions and function declarations are parsed only once, while those defined by the Function constructor are not. That is, the function body string passed to the Function constructor must be parsed each and every time the constructor is called. Although a function expression creates a closure every time, the function body is not reparsed, so function expressions are still faster than "new Function(...)". Therefore the Function constructor should generally be avoided whenever possible.

- -

It should be noted, however, that function expressions and function declarations nested within the function generated by parsing a Function constructor 's string aren't parsed repeatedly. For example:

- -
var foo = (new Function("var bar = \'FOO!\';\nreturn(function() {\n\talert(bar);\n});"))();
-foo(); // The segment "function() {\n\talert(bar);\n}" of the function body string is not re-parsed.
- -

A function declaration is very easily (and often unintentionally) turned into a function expression. A function declaration ceases to be one when it either:

- - - -
var x = 0;               // source element
-if (x === 0) {           // source element
-   x = 10;               // not a source element
-   function boo() {}     // not a source element
-}
-function foo() {         // source element
-   var y = 20;           // source element
-   function bar() {}     // source element
-   while (y === 10) {    // source element
-      function blah() {} // not a source element
-      y++;               // not a source element
-   }
-}
-
- -

Examples

- -
// function declaration
-function foo() {}
-
-// function expression
-(function bar() {})
-
-// function expression
-x = function hello() {}
-
-
-if (x) {
-   // function expression
-   function world() {}
-}
-
-
-// function declaration
-function a() {
-   // function declaration
-   function b() {}
-   if (0) {
-      // function expression
-      function c() {}
-   }
-}
-
- -

Block-level functions

- -

In strict mode, starting with ES2015, functions inside blocks are now scoped to that block. Prior to ES2015, block-level functions were forbidden in strict mode.

- -
'use strict';
-
-function f() {
-  return 1;
-}
-
-{
-  function f() {
-    return 2;
-  }
-}
-
-f() === 1; // true
-
-// f() === 2 in non-strict mode
-
- -

Block-level functions in non-strict code

- -

In a word: Don't.

- -

In non-strict code, function declarations inside blocks behave strangely. For example:

- -
if (shouldDefineZero) {
-   function zero() {     // DANGER: compatibility risk
-      console.log("This is zero.");
-   }
-}
-
- -

ES2015 says that if shouldDefineZero is false, then zero should never be defined, since the block never executes. However, it's a new part of the standard. Historically, this was left unspecified, and some browsers would define zero whether the block executed or not.

- -

In strict mode, all browsers that support ES2015 handle this the same way: zero is defined only if shouldDefineZero is true, and only in the scope of the if-block.

- -

A safer way to define functions conditionally is to assign a function expression to a variable:

- -
var zero;
-if (shouldDefineZero) {
-   zero = function() {
-      console.log("This is zero.");
-   };
-}
-
- -

Exemplos

- -

Returning a formatted number

- -

The following function returns a string containing the formatted representation of a number padded with leading zeros.

- -
// This function returns a string padded with leading zeros
-function padZeros(num, totalLen) {
-   var numStr = num.toString();             // Initialize return value as string
-   var numZeros = totalLen - numStr.length; // Calculate no. of zeros
-   for (var i = 1; i <= numZeros; i++) {
-      numStr = "0" + numStr;
-   }
-   return numStr;
-}
-
- -

The following statements call the padZeros function.

- -
var result;
-result = padZeros(42,4); // returns "0042"
-result = padZeros(42,2); // returns "42"
-result = padZeros(5,4);  // returns "0005"
-
- -

Determining whether a function exists

- -

You can determine whether a function exists by using the typeof operator. In the following example, a test is performed to determine if the window object has a property called noFunc that is a function. If so, it is used; otherwise some other action is taken.

- -
 if ('function' === typeof window.noFunc) {
-   // use noFunc()
- } else {
-   // do something else
- }
-
- -

Note that in the if test, a reference to noFunc is used—there are no brackets "()" after the function name so the actual function is not called.

- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0
{{SpecName('ES5.1', '#sec-13', 'Function Definition')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ES6')}}New: Arrow functions, Generator functions, default parameters, rest parameters.
{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ESDraft')}} 
- -

Compatibilidade de navegador

- - - -

{{Compat("javascript.functions")}}

- -

Consulte também

- - diff --git a/files/pt-pt/web/javascript/reference/funcoes/parametros_rest/index.html b/files/pt-pt/web/javascript/reference/funcoes/parametros_rest/index.html deleted file mode 100644 index a21cb25ed6..0000000000 --- a/files/pt-pt/web/javascript/reference/funcoes/parametros_rest/index.html +++ /dev/null @@ -1,234 +0,0 @@ ---- -title: Parâmetros Rest -slug: Web/JavaScript/Reference/Funcoes/parametros_rest -tags: - - Funcionalidade Linguagem - - Funções - - JavaScript - - Parametros Rest - - Rest -translation_of: Web/JavaScript/Reference/Functions/rest_parameters ---- -
Parâmetrois {{jsSidebar("Functions")}}
- -

A sintaxe do parâmetro "rest" permite-nos representar um número indefinido de argumentoscomo um array.

- -
{{EmbedInteractiveExample("pages/js/functions-restparameters.html")}}
- - - -

Sintaxe

- -
function f(a, b, ...theArgs) {
-  // ...
-}
- -

Descrição

- -

A function's last parameter can be prefixed with ... which will cause all remaining (user supplied) arguments to be placed within a "standard" Javascript array.

- -

Only the last parameter can be a "rest parameter".

- -
function myFun(a, b, ...manyMoreArgs) {
-  console.log("a", a)
-  console.log("b", b)
-  console.log("manyMoreArgs", manyMoreArgs)
-}
-
-myFun("one", "two", "three", "four", "five", "six")
-
-// Console Output:
-// a, one
-// b, two
-// manyMoreArgs, [three, four, five, six]
-
- -

Difference between rest parameters and the arguments object

- -

There are three main differences between rest parameters and the {{jsxref("Functions/arguments", "arguments")}} object:

- - - -

From arguments to an array

- -

Rest parameters have been introduced to reduce the boilerplate code that was induced by the arguments

- -
// Before rest parameters, "arguments" could be converted to a normal array using:
-
-function f(a, b) {
-
-  let normalArray = Array.prototype.slice.call(arguments)
-  // -- or --
-  let normalArray = [].slice.call(arguments)
-  // -- or --
-  let normalArray = Array.from(arguments)
-
-  let first = normalArray.shift()  // OK, gives the first argument
-  let first = arguments.shift()    // ERROR (arguments is not a normal array)
-}
-
-// Now, you can easily gain access to a normal array using a rest parameter
-
-function f(...args) {
-  let normalArray = args
-  let first = normalArray.shift() // OK, gives the first argument
-}
-
- -

Destructuring rest parameters

- -

Rest parameters can be destructured Arrays only (though objects will soon be supported). That means that their data can be unpacked into distinct variables. (See Destructuring assignment.)

- -
function f(...[a, b, c]) {
-  return a + b + c;
-}
-
-f(1)          // NaN (b and c are undefined)
-f(1, 2, 3)    // 6
-f(1, 2, 3, 4) // 6 (the fourth parameter is not destructured)
-
- -
-

Fixme

- -

Doing this is possible, but (afaik) there's no use-case, so it's just confusing the junior audience. The following code does exactly the same. There should at least be a note, that in theory you can do something like this, but there is no point in doing so. The example is contrived, but imagine that [a, b, c] were the return value of some function. Then the utility is clear.

- -

Also, since Function arguments will never have named parameters (this is not Python), the statement "objects will soon be supported" is wrong. The preceding example may be mixing up destructuring with rest parameters. Please see the page on destructuring assignment for an example with object destructuring applied in the parameters area.

- -
function f(a, b, c) {
-  return a + b + c
-}
-
-f(1)          // NaN (b and c are undefined)
-f(1, 2, 3)    // 6
-f(1, 2, 3, 4) // 6 (the fourth parameter is not ...)
-
-
- -

Exemplos

- -

In this example, the first argument is mapped to a and the second to b, so these named arguments are used like normal.

- -

However, the third argument, manyMoreArgs, will be an array that contains the 3rd, 4th, 5th, 6th ... nth — as many arguments that the user includes.

- -
function myFun(a, b, ...manyMoreArgs) {
-  console.log("a", a)
-  console.log("b", b)
-  console.log("manyMoreArgs", manyMoreArgs)
-}
-
-myFun("one", "two", "three", "four", "five", "six")
-
-// a, one
-// b, two
-// manyMoreArgs, [three, four, five, six]
-
- -

Below... even though there is just one value, the last argument still gets put into an array.

- -
// using the same function definition from example above
-
-myFun("one", "two", "three")
-
-// a, one
-// b, two
-// manyMoreArgs, [three]
- -

Below, the third argument isn't provided, but manyMoreArgs is still an array (albeit an empty one).

- -
// using the same function definition from example above
-
-myFun("one", "two")
-
-// a, one
-// b, two
-// manyMoreArgs, []
- -

Since theArgs is an array, a count of its elements is given by the length property:

- -
function fun1(...theArgs) {
-  console.log(theArgs.length)
-}
-
-fun1()         // 0
-fun1(5)        // 1
-fun1(5, 6, 7)  // 3
-
- -

In the next example, a rest parameter is used to collect all parameters after the first into an array. Each one of them is then multiplied by the first parameter, and the array is returned:

- -
function multiply(multiplier, ...theArgs) {
-  return theArgs.map(function(element) {
-    return multiplier * element
-  })
-}
-
-let arr = multiply(2, 1, 2, 3)
-console.log(arr)  // [2, 4, 6]
-
- -

Array methods can be used on rest parameters, but not on the arguments object:

- -
function sortRestArgs(...theArgs) {
-  let sortedArgs = theArgs.sort()
-  return sortedArgs
-}
-
-console.log(sortRestArgs(5, 3, 7, 1)) // 1, 3, 5, 7
-
-function sortArguments() {
-  let sortedArgs = arguments.sort()
-  return sortedArgs  // this will never happen
-}
-
-
-console.log(sortArguments(5, 3, 7, 1))
-// throws a TypeError (arguments.sort is not a function)
-
- -

To use Array methods on the arguments object, it must be converted to a real array first.

- -
function sortArguments() {
-  let args = Array.from(arguments)
-  let sortedArgs = args.sort()
-  return sortedArgs
-}
-console.log(sortArguments(5, 3, 7, 1))  // 1, 3, 5, 7
-
- -

Especificações

- - - - - - - - - - - - -
Especificação
{{SpecName('ESDraft', '#sec-function-definitions', 'Function Definitions')}}
- -

Compatibildiade de navegador

- - - -

{{Compat("javascript.functions.rest_parameters")}}

- -

Consulte também

- - diff --git a/files/pt-pt/web/javascript/reference/functions/arguments/index.html b/files/pt-pt/web/javascript/reference/functions/arguments/index.html new file mode 100644 index 0000000000..c7ac84a4b9 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/functions/arguments/index.html @@ -0,0 +1,228 @@ +--- +title: O objeto arguments +slug: Web/JavaScript/Reference/Funcoes/arguments +tags: + - Class + - Funções + - JavaScript + - Referencia + - arguments +translation_of: Web/JavaScript/Reference/Functions/arguments +--- +

{{JSSidebar("Functions")}}

+ +

arguments é um objeto semelhante a uma "Matiz" acessível dentro de functions que contém os valores dos argumentos passados ​​para essa função.

+ +
+

Nota: If you're writing ES6 compatible code, then rest parameters should be preferred.

+
+ +
+

Nota: “Array-like” means that arguments has a length property and properties indexed from zero, but it doesn't have {{JSxRef("Array")}}'s built-in methods like forEach and map. See §Description for details.

+
+ +
{{EmbedInteractiveExample("pages/js/functions-arguments.html")}}
+ + + +

Sintaxe

+ +
arguments
+ +

Descrição

+ +

The arguments object is a local variable available within all non-arrow functions. You can refer to a function's arguments inside that function by using its arguments object. It has entries for each argument the function was called with, with the first entry's index at 0.

+ +

For example, if a function is passed 3 arguments, you can access them as follows:

+ +
arguments[0] // first argument
+arguments[1] // second argument
+arguments[2] // third argument
+
+ +

Each argument can also be set or reassigned:

+ +
arguments[1] = 'new value';
+
+ +

The arguments object is not an {{JSxRef("Array")}}. It is similar, but does not have any Array properties except length. For example, it does not have the pop method. However, it can be converted to a real Array:

+ +
var args = Array.prototype.slice.call(arguments);
+// Using an array literal is shorter than above but allocates an empty array
+var args = [].slice.call(arguments);
+
+ +

As you can do with any Array-like object, you can use ES2015's {{JSxRef("Array.from()")}} method or spread operator to convert arguments to a real Array:

+ +
let args = Array.from(arguments);
+// or
+let args = [...arguments];
+ +

The arguments object is useful for functions called with more arguments than they are formally declared to accept. This technique is useful for functions that can be passed a variable number of arguments, such as Math.min(). This example function accepts any number of string arguments and returns the longest one:

+ +
function longestString() {
+  var longest = '';
+  for (var i=0; i < arguments.length; i++) {
+    if (arguments[i].length > longest.length) {
+      longest = arguments[i];
+    }
+  }
+  return longest;
+}
+
+ +

You can use arguments.length to count how many arguments the function was called with. If you instead want to count how many parameters a function is declared to accept, inspect that function's length property.

+ +

Utilizar typeof com Arguments

+ +

The typeof operator returns 'object' when used with arguments

+ +
console.log(typeof arguments); // 'object' 
+ +

The type of individual arguments can be determined by indexing arguments:

+ +
console.log(typeof arguments[0]); // returns the type of the first argument
+ +

Propriedades

+ +
+
+
{{jsxref("Functions/arguments/callee", "arguments.callee")}}
+
Reference to the currently executing function that the arguments belong to.
+
{{jsxref("Functions/arguments/length", "arguments.length")}}
+
The number of arguments that were passed to the function.
+
{{jsxref("Functions/arguments/@@iterator", "arguments[@@iterator]")}}
+
Returns a new {{jsxref("Array/@@iterator", "Array iterator", "", 0)}} object that contains the values for each index in arguments.
+
+ +

Exemplos

+ +

Definir uma function que concatena várias strings

+ +

This example defines a function that concatenates several strings. The function's only formal argument is a string containing the characters that separate the items to concatenate.

+ +
function myConcat(separator) {
+  var args = Array.prototype.slice.call(arguments, 1);
+  return args.join(separator);
+}
+ +

You can pass as many arguments as you like to this function. It returns a string list using each argument in the list:

+ +
// returns "red, orange, blue"
+myConcat(', ', 'red', 'orange', 'blue');
+
+// returns "elephant; giraffe; lion; cheetah"
+myConcat('; ', 'elephant', 'giraffe', 'lion', 'cheetah');
+
+// returns "sage. basil. oregano. pepper. parsley"
+myConcat('. ', 'sage', 'basil', 'oregano', 'pepper', 'parsley');
+ +

Definir uma function que cria listas HTML

+ +

This example defines a function that creates a string containing HTML for a list. The only formal argument for the function is a string that is "u" if the list is to be unordered (bulleted), or "o" if the list is to be ordered (numbered). The function is defined as follows:

+ +
function list(type) {
+  var html = '<' + type + 'l><li>';
+  var args = Array.prototype.slice.call(arguments, 1);
+  html += args.join('</li><li>');
+  html += '</li></' + type + 'l>'; // end list
+
+  return html;
+}
+ +

You can pass any number of arguments to this function, and it adds each argument as a list item to a list of the type indicated. For example:

+ +
var listHTML = list('u', 'One', 'Two', 'Three');
+
+/* listHTML is:
+"<ul><li>One</li><li>Two</li><li>Three</li></ul>"
+*/
+ +

Parâmetros Rest, predefinição, e desestruturados

+ +

The arguments object can be used in conjunction with rest, default, and destructured parameters.

+ +
function foo(...args) {
+  return args;
+}
+foo(1, 2, 3); // [1,2,3]
+
+ +

While the presence of rest, default, or destructured parameters does not alter the behavior of the arguments object in strict mode code, there is a subtle difference for non-strict code.

+ +

In strict-mode code, the arguments object behaves the same whether or not a function is passed rest, default, or destructured parameters. That is, assigning new values to variables in the body of the function will not affect the arguments object. Nor will assigning new variables to the arguments object affect the value of variables.

+ +
+

Nota: You cannot write a "use strict"; directive in the body of a function definition that accepts rest, default, or destructured parameters. Doing so will throw a syntax error.

+
+ +

Non-strict functions that are passed only simple parameters (that is, not rest, default, or restructured parameters) will sync the value of variables new values in the body of the function with the arguments object, and vice versa:

+ +
function func(a) {
+  arguments[0] = 99; // updating arguments[0] also updates a
+  console.log(a);
+}
+func(10); // 99
+
+ +

And also:

+ +
function func(a) {
+  a = 99; // updating a also updates arguments[0]
+  console.log(arguments[0]);
+}
+func(10); // 99
+
+ +

Conversely, non-strict functions that are passed rest, default, or destructured parameters will not sync new values assigned to argument variables in the function body with the arguments object. Instead, the arguments object in non-strict functions with complex parameters will always reflect the values passed to the function when the function was called (this is the same behavior as exhibited by all strict-mode functions, regardless of the type of variables they are passed):

+ +
function func(a = 55) {
+  arguments[0] = 99; // updating arguments[0] does not also update a
+  console.log(a);
+}
+func(10); // 10
+ +

E também:

+ +
function func(a = 55) {
+  a = 99; // updating a does not also update arguments[0]
+  console.log(arguments[0]);
+}
+func(10); // 10
+
+ +

E também:

+ +
// An untracked default parameter
+function func(a = 55) {
+  console.log(arguments[0]);
+}
+func(); // undefined
+ +

Especificações

+ + + + + + + + + + + + +
Especificação
{{SpecName('ESDraft', '#sec-arguments-exotic-objects', 'Arguments Exotic Objects')}}
+ +

Compatibildiade de navegador

+ + + +

{{Compat("javascript.functions.arguments")}}

+ +

Consulte também

+ + diff --git a/files/pt-pt/web/javascript/reference/functions/arrow_functions/index.html b/files/pt-pt/web/javascript/reference/functions/arrow_functions/index.html new file mode 100644 index 0000000000..aa7b7b3121 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/functions/arrow_functions/index.html @@ -0,0 +1,399 @@ +--- +title: Expressões da função "Seta" +slug: Web/JavaScript/Reference/Funcoes/Funcoes_seta +translation_of: Web/JavaScript/Reference/Functions/Arrow_functions +--- +
{{jsSidebar("Functions")}}
+ +

Uma expressão da função seta é uma alternativa sintaticamente compacta a uma expressão de expressão de função regular, embora sem as suas próprias associações às palavras-chave this, arguments, super, ou new.target. As expressões de função (function) de seta são inadequadas como métodos, e não podem ser utilziadas como construtores.

+ +
{{EmbedInteractiveExample("pages/js/functions-arrow.html")}}
+ +

Sintaxe

+ +

Basic syntax

+ +
(param1, param2, …, paramN) => { statements }
+(param1, param2, …, paramN) => expression
+// equivalent to: => { return expression; }
+
+// Parentheses are optional when there's only one parameter name:
+(singleParam) => { statements }
+singleParam => { statements }
+
+// The parameter list for a function with no parameters should be written with a pair of parentheses.
+() => { statements }
+
+ +

Advanced syntax

+ +
// Parenthesize the body of a function to return an object literal expression:
+params => ({foo: bar})
+
+// Rest parameters and default parameters are supported
+(param1, param2, ...rest) => { statements }
+(param1 = defaultValue1, param2, …, paramN = defaultValueN) => {
+statements }
+
+// Destructuring within the parameter list is also supported
+var f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c;
+f(); // 6
+
+ +

Descrição

+ +

See also "ES6 In Depth: Arrow functions" on hacks.mozilla.org.

+ +

Two factors influenced the introduction of arrow functions: the need for shorter functions and the behavior of the this keyword.

+ +

Funções curtas

+ +
var elements = [
+  'Hydrogen',
+  'Helium',
+  'Lithium',
+  'Beryllium'
+];
+
+// This statement returns the array: [8, 6, 7, 9]
+elements.map(function(element) {
+  return element.length;
+});
+
+// The regular function above can be written as the arrow function below
+elements.map((element) => {
+  return element.length;
+}); // [8, 6, 7, 9]
+
+// When there is only one parameter, we can remove the surrounding parentheses
+elements.map(element => {
+  return element.length;
+}); // [8, 6, 7, 9]
+
+// When the only statement in an arrow function is `return`, we can remove `return` and remove
+// the surrounding curly brackets
+elements.map(element => element.length); // [8, 6, 7, 9]
+
+// In this case, because we only need the length property, we can use destructuring parameter:
+// Notice that the `length` corresponds to the property we want to get whereas the
+// obviously non-special `lengthFooBArX` is just the name of a variable which can be changed
+// to any valid variable name you want
+elements.map(({ length: lengthFooBArX }) => lengthFooBArX); // [8, 6, 7, 9]
+
+// This destructuring parameter assignment can also be written as seen below. However, note that in
+// this example we are not assigning `length` value to the made up property. Instead, the literal name
+// itself of the variable `length` is used as the property we want to retrieve from the object.
+elements.map(({ length }) => length); // [8, 6, 7, 9]
+
+ +

No separate this

+ +

Before arrow functions, every new function defined its own this value based on how the function was called:

+ + + +

This proved to be less than ideal with an object-oriented style of programming.

+ +
function Person() {
+  // The Person() constructor defines `this` as an instance of itself.
+  this.age = 0;
+
+  setInterval(function growUp() {
+    // In non-strict mode, the growUp() function defines `this`
+    // as the global object (because it's where growUp() is executed.),
+    // which is different from the `this`
+    // defined by the Person() constructor.
+    this.age++;
+  }, 1000);
+}
+
+var p = new Person();
+ +

In ECMAScript 3/5, the this issue was fixable by assigning the value in this to a variable that could be closed over.

+ +
function Person() {
+  var that = this;
+  that.age = 0;
+
+  setInterval(function growUp() {
+    // The callback refers to the `that` variable of which
+    // the value is the expected object.
+    that.age++;
+  }, 1000);
+}
+ +

Alternatively, a bound function could be created so that a preassigned this value would be passed to the bound target function (the growUp() function in the example above).

+ +

An arrow function does not have its own this. The this value of the enclosing lexical scope is used; arrow functions follow the normal variable lookup rules. So while searching for this which is not present in current scope, an arrow function ends up finding the this from its enclosing scope.

+ +

Thus, in the following code, the this within the function that is passed to setInterval has the same value as the this in the lexically enclosing function:

+ +
function Person(){
+  this.age = 0;
+
+  setInterval(() => {
+    this.age++; // |this| properly refers to the Person object
+  }, 1000);
+}
+
+var p = new Person();
+ +

Relation with strict mode

+ +

Given that this comes from the surrounding lexical context, strict mode rules with regard to this are ignored.

+ +
var f = () => { 'use strict'; return this; };
+f() === window; // or the global object
+ +

All other strict mode rules apply normally.

+ +

Invoked through call or apply

+ +

Since arrow functions do not have their own this, the methods call() and apply() can only pass in parameters. Any this argument is ignored.

+ +
var adder = {
+  base: 1,
+
+  add: function(a) {
+    var f = v => v + this.base;
+    return f(a);
+  },
+
+  addThruCall: function(a) {
+    var f = v => v + this.base;
+    var b = {
+      base: 2
+    };
+
+    return f.call(b, a);
+  }
+};
+
+console.log(adder.add(1));         // This would log 2
+console.log(adder.addThruCall(1)); // This would log 2 still
+ +

No binding of arguments

+ +

Arrow functions do not have their own arguments object. Thus, in this example, arguments is simply a reference to the arguments of the enclosing scope:

+ +
var arguments = [1, 2, 3];
+var arr = () => arguments[0];
+
+arr(); // 1
+
+function foo(n) {
+  var f = () => arguments[0] + n; // foo's implicit arguments binding. arguments[0] is n
+  return f();
+}
+
+foo(3); // 6
+ +

In most cases, using rest parameters is a good alternative to using an arguments object.

+ +
function foo(n) {
+  var f = (...args) => args[0] + n;
+  return f(10);
+}
+
+foo(1); // 11
+ +

Arrow functions used as methods

+ +

As stated previously, arrow function expressions are best suited for non-method functions. Let's see what happens when we try to use them as methods:

+ +
'use strict';
+
+var obj = { // does not create a new scope
+  i: 10,
+  b: () => console.log(this.i, this),
+  c: function() {
+    console.log(this.i, this);
+  }
+}
+
+obj.b(); // prints undefined, Window {...} (or the global object)
+obj.c(); // prints 10, Object {...}
+ +

Arrow functions do not have their own this. Another example involving {{jsxref("Object.defineProperty()")}}:

+ +
'use strict';
+
+var obj = {
+  a: 10
+};
+
+Object.defineProperty(obj, 'b', {
+  get: () => {
+    console.log(this.a, typeof this.a, this); // undefined 'undefined' Window {...} (or the global object)
+    return this.a + 10; // represents global object 'Window', therefore 'this.a' returns 'undefined'
+  }
+});
+
+ +

Use of the new operator

+ +

Arrow functions cannot be used as constructors and will throw an error when used with new.

+ +
var Foo = () => {};
+var foo = new Foo(); // TypeError: Foo is not a constructor
+ +

Use of prototype property

+ +

Arrow functions do not have a prototype property.

+ +
var Foo = () => {};
+console.log(Foo.prototype); // undefined
+
+ +

Use of the yield keyword

+ +

The yield keyword may not be used in an arrow function's body (except when permitted within functions further nested within it). As a consequence, arrow functions cannot be used as generators.

+ +

Function body

+ +

Arrow functions can have either a "concise body" or the usual "block body".

+ +

In a concise body, only an expression is specified, which becomes the implicit return value. In a block body, you must use an explicit return statement.

+ +
var func = x => x * x;
+// concise body syntax, implied "return"
+
+var func = (x, y) => { return x + y; };
+// with block body, explicit "return" needed
+
+ +

Returning object literals

+ +

Keep in mind that returning object literals using the concise body syntax params => {object:literal} will not work as expected.

+ +
var func = () => { foo: 1 };
+// Calling func() returns undefined!
+
+var func = () => { foo: function() {} };
+// SyntaxError: function statement requires a name
+ +

This is because the code inside braces ({}) is parsed as a sequence of statements (i.e. foo is treated like a label, not a key in an object literal).

+ +

You must wrap the object literal in parentheses:

+ +
var func = () => ({ foo: 1 });
+ +

Line breaks

+ +

An arrow function cannot contain a line break between its parameters and its arrow.

+ +
var func = (a, b, c)
+  => 1;
+// SyntaxError: expected expression, got '=>'
+ +

However, this can be amended by putting the line break after the arrow or using parentheses/braces as seen below to ensure that the code stays pretty and fluffy. You can also put line breaks between arguments.

+ +
var func = (a, b, c) =>
+  1;
+
+var func = (a, b, c) => (
+  1
+);
+
+var func = (a, b, c) => {
+  return 1
+};
+
+var func = (
+  a,
+  b,
+  c
+) => 1;
+
+// no SyntaxError thrown
+ +

Parsing order

+ +

Although the arrow in an arrow function is not an operator, arrow functions have special parsing rules that interact differently with operator precedence compared to regular functions.

+ +
let callback;
+
+callback = callback || function() {}; // ok
+
+callback = callback || () => {};
+// SyntaxError: invalid arrow-function arguments
+
+callback = callback || (() => {});    // ok
+
+ +

More examples

+ +
// An empty arrow function returns undefined
+let empty = () => {};
+
+(() => 'foobar')();
+// Returns "foobar"
+// (this is an Immediately Invoked Function Expression)
+
+var simple = a => a > 15 ? 15 : a;
+simple(16); // 15
+simple(10); // 10
+
+let max = (a, b) => a > b ? a : b;
+
+// Easy array filtering, mapping, ...
+
+var arr = [5, 6, 13, 0, 1, 18, 23];
+
+var sum = arr.reduce((a, b) => a + b);
+// 66
+
+var even = arr.filter(v => v % 2 == 0);
+// [6, 0, 18]
+
+var double = arr.map(v => v * 2);
+// [10, 12, 26, 0, 2, 36, 46]
+
+// More concise promise chains
+promise.then(a => {
+  // ...
+}).then(b => {
+  // ...
+});
+
+// Parameterless arrow functions that are visually easier to parse
+setTimeout( () => {
+  console.log('I happen sooner');
+  setTimeout( () => {
+    // deeper code
+    console.log('I happen later');
+  }, 1);
+}, 1);
+
+ +

Specifications

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-arrow-function-definitions', 'Arrow Function Definitions')}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.functions.arrow_functions")}}

+
+ +

See also

+ + diff --git a/files/pt-pt/web/javascript/reference/functions/index.html b/files/pt-pt/web/javascript/reference/functions/index.html new file mode 100644 index 0000000000..02b35fc7bd --- /dev/null +++ b/files/pt-pt/web/javascript/reference/functions/index.html @@ -0,0 +1,594 @@ +--- +title: Funções +slug: Web/JavaScript/Reference/Funcoes +tags: + - Constructor + - Função + - Funções + - JavaScript + - Parâmetro + - parâmetros +translation_of: Web/JavaScript/Reference/Functions +--- +
{{jsSidebar("Functions")}}
+ +

Generally speaking, a function is a "subprogram" that can be called by code external (or internal in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the function body. Values can be passed to a function, and the function will return a value.

+ +

In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects.

+ +

For more examples and explanations, see also the JavaScript guide about functions.

+ +

Descrição

+ +

Every function in JavaScript is a Function object. See {{jsxref("Function")}} for information on properties and methods of Function objects.

+ +

To return a value other than the default, a function must have a return statement that specifies the value to return. A function without a return statement will return a default value. In the case of a constructor called with the new keyword, the default value is the value of its this parameter. For all other functions, the default return value is {{jsxref("undefined")}}.

+ +

The parameters of a function call are the function's arguments. Arguments are passed to functions by value. If the function changes the value of an argument, this change is not reflected globally or in the calling function. However, object references are values, too, and they are special: if the function changes the referred object's properties, that change is visible outside the function, as shown in the following example:

+ +
/* Declare the function 'myFunc' */
+function myFunc(theObject) {
+  theObject.brand = "Toyota";
+}
+
+/*
+ * Declare variable 'mycar';
+ * create and initialize a new Object;
+ * assign reference to it to 'mycar'
+ */
+var mycar = {
+  brand: "Honda",
+  model: "Accord",
+  year: 1998
+};
+
+/* Logs 'Honda' */
+console.log(mycar.brand);
+
+/* Pass object reference to the function */
+myFunc(mycar);
+
+/*
+ * Logs 'Toyota' as the value of the 'brand' property
+ * of the object, as changed to by the function.
+ */
+console.log(mycar.brand);
+
+ +

The this keyword does not refer to the currently executing function, so you must refer to Function objects by name, even within the function body.

+ +

Definindo funções

+ +

There are several ways to define functions:

+ +

The function declaration (function statement)

+ +

There is a special syntax for declaring functions (see function statement for details):

+ +
function name([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
The function name.
+
+ +
+
param
+
The name of an argument to be passed to the function. A function can have up to 255 arguments.
+
+ +
+
statements
+
The statements comprising the body of the function.
+
+ +

The function expression (function expression)

+ +

A function expression is similar to and has the same syntax as a function declaration (see function expression for details). A function expression may be a part of a larger expression. One can define "named" function expressions (where the name of the expression might be used in the call stack for example) or "anonymous" function expressions. Function expressions are not hoisted onto the beginning of the scope, therefore they cannot be used before they appear in the code.

+ +
function [name]([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
+
+ +
+
param
+
The name of an argument to be passed to the function. A function can have up to 255 arguments.
+
statements
+
The statements comprising the body of the function.
+
+ +

Here is an example of an anonymous function expression (the name is not used):

+ +
var myFunction = function() {
+    statements
+}
+ +

It is also possible to provide a name inside the definition in order to create a named function expression:

+ +
var myFunction = function namedFunction(){
+    statements
+}
+
+ +

One of the benefit of creating a named function expression is that in case we encounted an error, the stack trace will contain the name of the function, making it easier to find the origin of the error.

+ +

As we can see, both examples do not start with the function keyword. Statements involving functions which do not start with function are function expressions.

+ +

When functions are used only once, a common pattern is an IIFE (Immediately Invokable Function Expression).

+ +
(function() {
+    statements
+})();
+ +

IIFE are function expressions that are invoked as soon as the function is declared.

+ +

The generator function declaration (function* statement)

+ +

There is a special syntax for generator function declarations (see {{jsxref('Statements/function*', 'function* statement')}} for details):

+ +
function* name([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
The function name.
+
+ +
+
param
+
The name of an argument to be passed to the function. A function can have up to 255 arguments.
+
+ +
+
statements
+
The statements comprising the body of the function.
+
+ +

The generator function expression (function* expression)

+ +

A generator function expression is similar to and has the same syntax as a generator function declaration (see {{jsxref('Operators/function*', 'function* expression')}} for details):

+ +
function* [name]([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
+
+ +
+
param
+
The name of an argument to be passed to the function. A function can have up to 255 arguments.
+
statements
+
The statements comprising the body of the function.
+
+ +

The arrow function expression (=>)

+ +

An arrow function expression has a shorter syntax and lexically binds its this value (see arrow functions for details):

+ +
([param[, param]]) => {
+   statements
+}
+
+param => expression
+
+ +
+
param
+
The name of an argument. Zero arguments need to be indicated with ().  For only one argument, the parentheses are not required. (like foo => 1)
+
statements or expression
+
Multiple statements need to be enclosed in brackets. A single expression requires no brackets. The expression is also the implicit return value of the function.
+
+ +

The Function constructor

+ +
+

Note: Using the Function constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.

+
+ +

As all other objects, {{jsxref("Function")}} objects can be created using the new operator:

+ +
new Function (arg1, arg2, ... argN, functionBody)
+
+ +
+
arg1, arg2, ... argN
+
Zero or more names to be used by the function as formal parameters. Each must be a proper JavaScript identifier.
+
+ +
+
functionBody
+
A string containing the JavaScript statements comprising the function body.
+
+ +

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

+ +

The GeneratorFunction constructor

+ +
+

Note: GeneratorFunction is not a global object, but could be obtained from generator function instance (see {{jsxref("GeneratorFunction")}} for more detail).

+
+ +
+

Note: Using the GeneratorFunction constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.

+
+ +

As all other objects, {{jsxref("GeneratorFunction")}} objects can be created using the new operator:

+ +
new GeneratorFunction (arg1, arg2, ... argN, functionBody)
+
+ +
+
arg1, arg2, ... argN
+
Zero or more names to be used by the function as formal argument names. Each must be a string that conforms to the rules for a valid JavaScript identifier or a list of such strings separated with a comma; for example "x", "theValue", or "a,b".
+
+ +
+
functionBody
+
A string containing the JavaScript statements comprising the function definition.
+
+ +

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

+ +

Parâmetros de função

+ +

Parâmetros predefinidos

+ +

Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed. For more details, see default parameters.

+ +

Parâmetros Rest

+ +

The rest parameter syntax allows to represent an indefinite number of arguments as an array. For more details, see rest parameters.

+ +

O objeto arguments

+ +

You can refer to a function's arguments within the function by using the arguments object. See arguments.

+ + + +

Definindo funções de método

+ +

Getter and setter functions

+ +

You can define getters (accessor methods) and setters (mutator methods) on any standard built-in object or user-defined object that supports the addition of new properties. The syntax for defining getters and setters uses the object literal syntax.

+ +
+
get
+
+

Binds an object property to a function that will be called when that property is looked up.

+
+
set
+
Binds an object property to a function to be called when there is an attempt to set that property.
+
+ +

Method definition syntax

+ +

Starting with ECMAScript 2015, you are able to define own methods in a shorter syntax, similar to the getters and setters. See method definitions for more information.

+ +
var obj = {
+  foo() {},
+  bar() {}
+};
+ +

Constructor vs. declaration vs. expression

+ +

Compare the following:

+ +

A function defined with the Function constructor assigned to the variable multiply:

+ +
var multiply = new Function('x', 'y', 'return x * y');
+ +

A function declaration of a function named multiply:

+ +
function multiply(x, y) {
+   return x * y;
+} // there is no semicolon here
+
+ +

A function expression of an anonymous function assigned to the variable multiply:

+ +
var multiply = function(x, y) {
+   return x * y;
+};
+
+ +

A function expression of a function named func_name assigned to the variable multiply:

+ +
var multiply = function func_name(x, y) {
+   return x * y;
+};
+
+ +

Differences

+ +

All do approximately the same thing, with a few subtle differences:

+ +

There is a distinction between the function name and the variable the function is assigned to. The function name cannot be changed, while the variable the function is assigned to can be reassigned. The function name can be used only within the function's body. Attempting to use it outside the function's body results in an error (or undefined if the function name was previously declared via a var statement). For example:

+ +
var y = function x() {};
+alert(x); // throws an error
+
+ +

The function name also appears when the function is serialized via Function's toString method.

+ +

On the other hand, the variable the function is assigned to is limited only by its scope, which is guaranteed to include the scope in which the function is declared.

+ +

As the 4th example shows, the function name can be different from the variable the function is assigned to. They have no relation to each other. A function declaration also creates a variable with the same name as the function name. Thus, unlike those defined by function expressions, functions defined by function declarations can be accessed by their name in the scope they were defined in:

+ +

A function defined by 'new Function' does not have a function name. However, in the SpiderMonkey JavaScript engine, the serialized form of the function shows as if it has the name "anonymous". For example, alert(new Function()) outputs:

+ +
function anonymous() {
+}
+
+ +

Since the function actually does not have a name, anonymous is not a variable that can be accessed within the function. For example, the following would result in an error:

+ +
var foo = new Function("alert(anonymous);");
+foo();
+
+ +

Unlike functions defined by function expressions or by the Function constructor, a function defined by a function declaration can be used before the function declaration itself. For example:

+ +
foo(); // alerts FOO!
+function foo() {
+   alert('FOO!');
+}
+
+ +

A function defined by a function expression or by a function declaration inherits the current scope. That is, the function forms a closure. On the other hand, a function defined by a Function constructor does not inherit any scope other than the global scope (which all functions inherit).

+ +
/*
+ * Declare and initialize a variable 'p' (global)
+ * and a function 'myFunc' (to change the scope) inside which
+ * declare a varible with same name 'p' (current) and
+ * define three functions using three different ways:-
+ *     1. function declaration
+ *     2. function expression
+ *     3. function constructor
+ * each of which will log 'p'
+ */
+var p = 5;
+function myFunc() {
+    var p = 9;
+
+    function decl() {
+        console.log(p);
+    }
+    var expr = function() {
+        console.log(p);
+    };
+    var cons = new Function('\tconsole.log(p);');
+
+    decl();
+    expr();
+    cons();
+}
+myFunc();
+
+/*
+ * Logs:-
+ * 9  - for 'decl' by function declaration (current scope)
+ * 9  - for 'expr' by function expression (current scope)
+ * 5  - for 'cons' by Function constructor (global scope)
+ */
+
+ +

Functions defined by function expressions and function declarations are parsed only once, while those defined by the Function constructor are not. That is, the function body string passed to the Function constructor must be parsed each and every time the constructor is called. Although a function expression creates a closure every time, the function body is not reparsed, so function expressions are still faster than "new Function(...)". Therefore the Function constructor should generally be avoided whenever possible.

+ +

It should be noted, however, that function expressions and function declarations nested within the function generated by parsing a Function constructor 's string aren't parsed repeatedly. For example:

+ +
var foo = (new Function("var bar = \'FOO!\';\nreturn(function() {\n\talert(bar);\n});"))();
+foo(); // The segment "function() {\n\talert(bar);\n}" of the function body string is not re-parsed.
+ +

A function declaration is very easily (and often unintentionally) turned into a function expression. A function declaration ceases to be one when it either:

+ + + +
var x = 0;               // source element
+if (x === 0) {           // source element
+   x = 10;               // not a source element
+   function boo() {}     // not a source element
+}
+function foo() {         // source element
+   var y = 20;           // source element
+   function bar() {}     // source element
+   while (y === 10) {    // source element
+      function blah() {} // not a source element
+      y++;               // not a source element
+   }
+}
+
+ +

Examples

+ +
// function declaration
+function foo() {}
+
+// function expression
+(function bar() {})
+
+// function expression
+x = function hello() {}
+
+
+if (x) {
+   // function expression
+   function world() {}
+}
+
+
+// function declaration
+function a() {
+   // function declaration
+   function b() {}
+   if (0) {
+      // function expression
+      function c() {}
+   }
+}
+
+ +

Block-level functions

+ +

In strict mode, starting with ES2015, functions inside blocks are now scoped to that block. Prior to ES2015, block-level functions were forbidden in strict mode.

+ +
'use strict';
+
+function f() {
+  return 1;
+}
+
+{
+  function f() {
+    return 2;
+  }
+}
+
+f() === 1; // true
+
+// f() === 2 in non-strict mode
+
+ +

Block-level functions in non-strict code

+ +

In a word: Don't.

+ +

In non-strict code, function declarations inside blocks behave strangely. For example:

+ +
if (shouldDefineZero) {
+   function zero() {     // DANGER: compatibility risk
+      console.log("This is zero.");
+   }
+}
+
+ +

ES2015 says that if shouldDefineZero is false, then zero should never be defined, since the block never executes. However, it's a new part of the standard. Historically, this was left unspecified, and some browsers would define zero whether the block executed or not.

+ +

In strict mode, all browsers that support ES2015 handle this the same way: zero is defined only if shouldDefineZero is true, and only in the scope of the if-block.

+ +

A safer way to define functions conditionally is to assign a function expression to a variable:

+ +
var zero;
+if (shouldDefineZero) {
+   zero = function() {
+      console.log("This is zero.");
+   };
+}
+
+ +

Exemplos

+ +

Returning a formatted number

+ +

The following function returns a string containing the formatted representation of a number padded with leading zeros.

+ +
// This function returns a string padded with leading zeros
+function padZeros(num, totalLen) {
+   var numStr = num.toString();             // Initialize return value as string
+   var numZeros = totalLen - numStr.length; // Calculate no. of zeros
+   for (var i = 1; i <= numZeros; i++) {
+      numStr = "0" + numStr;
+   }
+   return numStr;
+}
+
+ +

The following statements call the padZeros function.

+ +
var result;
+result = padZeros(42,4); // returns "0042"
+result = padZeros(42,2); // returns "42"
+result = padZeros(5,4);  // returns "0005"
+
+ +

Determining whether a function exists

+ +

You can determine whether a function exists by using the typeof operator. In the following example, a test is performed to determine if the window object has a property called noFunc that is a function. If so, it is used; otherwise some other action is taken.

+ +
 if ('function' === typeof window.noFunc) {
+   // use noFunc()
+ } else {
+   // do something else
+ }
+
+ +

Note that in the if test, a reference to noFunc is used—there are no brackets "()" after the function name so the actual function is not called.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0
{{SpecName('ES5.1', '#sec-13', 'Function Definition')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ES6')}}New: Arrow functions, Generator functions, default parameters, rest parameters.
{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidade de navegador

+ + + +

{{Compat("javascript.functions")}}

+ +

Consulte também

+ + diff --git a/files/pt-pt/web/javascript/reference/functions/rest_parameters/index.html b/files/pt-pt/web/javascript/reference/functions/rest_parameters/index.html new file mode 100644 index 0000000000..a21cb25ed6 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/functions/rest_parameters/index.html @@ -0,0 +1,234 @@ +--- +title: Parâmetros Rest +slug: Web/JavaScript/Reference/Funcoes/parametros_rest +tags: + - Funcionalidade Linguagem + - Funções + - JavaScript + - Parametros Rest + - Rest +translation_of: Web/JavaScript/Reference/Functions/rest_parameters +--- +
Parâmetrois {{jsSidebar("Functions")}}
+ +

A sintaxe do parâmetro "rest" permite-nos representar um número indefinido de argumentoscomo um array.

+ +
{{EmbedInteractiveExample("pages/js/functions-restparameters.html")}}
+ + + +

Sintaxe

+ +
function f(a, b, ...theArgs) {
+  // ...
+}
+ +

Descrição

+ +

A function's last parameter can be prefixed with ... which will cause all remaining (user supplied) arguments to be placed within a "standard" Javascript array.

+ +

Only the last parameter can be a "rest parameter".

+ +
function myFun(a, b, ...manyMoreArgs) {
+  console.log("a", a)
+  console.log("b", b)
+  console.log("manyMoreArgs", manyMoreArgs)
+}
+
+myFun("one", "two", "three", "four", "five", "six")
+
+// Console Output:
+// a, one
+// b, two
+// manyMoreArgs, [three, four, five, six]
+
+ +

Difference between rest parameters and the arguments object

+ +

There are three main differences between rest parameters and the {{jsxref("Functions/arguments", "arguments")}} object:

+ + + +

From arguments to an array

+ +

Rest parameters have been introduced to reduce the boilerplate code that was induced by the arguments

+ +
// Before rest parameters, "arguments" could be converted to a normal array using:
+
+function f(a, b) {
+
+  let normalArray = Array.prototype.slice.call(arguments)
+  // -- or --
+  let normalArray = [].slice.call(arguments)
+  // -- or --
+  let normalArray = Array.from(arguments)
+
+  let first = normalArray.shift()  // OK, gives the first argument
+  let first = arguments.shift()    // ERROR (arguments is not a normal array)
+}
+
+// Now, you can easily gain access to a normal array using a rest parameter
+
+function f(...args) {
+  let normalArray = args
+  let first = normalArray.shift() // OK, gives the first argument
+}
+
+ +

Destructuring rest parameters

+ +

Rest parameters can be destructured Arrays only (though objects will soon be supported). That means that their data can be unpacked into distinct variables. (See Destructuring assignment.)

+ +
function f(...[a, b, c]) {
+  return a + b + c;
+}
+
+f(1)          // NaN (b and c are undefined)
+f(1, 2, 3)    // 6
+f(1, 2, 3, 4) // 6 (the fourth parameter is not destructured)
+
+ +
+

Fixme

+ +

Doing this is possible, but (afaik) there's no use-case, so it's just confusing the junior audience. The following code does exactly the same. There should at least be a note, that in theory you can do something like this, but there is no point in doing so. The example is contrived, but imagine that [a, b, c] were the return value of some function. Then the utility is clear.

+ +

Also, since Function arguments will never have named parameters (this is not Python), the statement "objects will soon be supported" is wrong. The preceding example may be mixing up destructuring with rest parameters. Please see the page on destructuring assignment for an example with object destructuring applied in the parameters area.

+ +
function f(a, b, c) {
+  return a + b + c
+}
+
+f(1)          // NaN (b and c are undefined)
+f(1, 2, 3)    // 6
+f(1, 2, 3, 4) // 6 (the fourth parameter is not ...)
+
+
+ +

Exemplos

+ +

In this example, the first argument is mapped to a and the second to b, so these named arguments are used like normal.

+ +

However, the third argument, manyMoreArgs, will be an array that contains the 3rd, 4th, 5th, 6th ... nth — as many arguments that the user includes.

+ +
function myFun(a, b, ...manyMoreArgs) {
+  console.log("a", a)
+  console.log("b", b)
+  console.log("manyMoreArgs", manyMoreArgs)
+}
+
+myFun("one", "two", "three", "four", "five", "six")
+
+// a, one
+// b, two
+// manyMoreArgs, [three, four, five, six]
+
+ +

Below... even though there is just one value, the last argument still gets put into an array.

+ +
// using the same function definition from example above
+
+myFun("one", "two", "three")
+
+// a, one
+// b, two
+// manyMoreArgs, [three]
+ +

Below, the third argument isn't provided, but manyMoreArgs is still an array (albeit an empty one).

+ +
// using the same function definition from example above
+
+myFun("one", "two")
+
+// a, one
+// b, two
+// manyMoreArgs, []
+ +

Since theArgs is an array, a count of its elements is given by the length property:

+ +
function fun1(...theArgs) {
+  console.log(theArgs.length)
+}
+
+fun1()         // 0
+fun1(5)        // 1
+fun1(5, 6, 7)  // 3
+
+ +

In the next example, a rest parameter is used to collect all parameters after the first into an array. Each one of them is then multiplied by the first parameter, and the array is returned:

+ +
function multiply(multiplier, ...theArgs) {
+  return theArgs.map(function(element) {
+    return multiplier * element
+  })
+}
+
+let arr = multiply(2, 1, 2, 3)
+console.log(arr)  // [2, 4, 6]
+
+ +

Array methods can be used on rest parameters, but not on the arguments object:

+ +
function sortRestArgs(...theArgs) {
+  let sortedArgs = theArgs.sort()
+  return sortedArgs
+}
+
+console.log(sortRestArgs(5, 3, 7, 1)) // 1, 3, 5, 7
+
+function sortArguments() {
+  let sortedArgs = arguments.sort()
+  return sortedArgs  // this will never happen
+}
+
+
+console.log(sortArguments(5, 3, 7, 1))
+// throws a TypeError (arguments.sort is not a function)
+
+ +

To use Array methods on the arguments object, it must be converted to a real array first.

+ +
function sortArguments() {
+  let args = Array.from(arguments)
+  let sortedArgs = args.sort()
+  return sortedArgs
+}
+console.log(sortArguments(5, 3, 7, 1))  // 1, 3, 5, 7
+
+ +

Especificações

+ + + + + + + + + + + + +
Especificação
{{SpecName('ESDraft', '#sec-function-definitions', 'Function Definitions')}}
+ +

Compatibildiade de navegador

+ + + +

{{Compat("javascript.functions.rest_parameters")}}

+ +

Consulte também

+ + diff --git a/files/pt-pt/web/javascript/reference/global_objects/asyncfunction/prototype/index.html b/files/pt-pt/web/javascript/reference/global_objects/asyncfunction/prototype/index.html deleted file mode 100644 index 8a085d6986..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/asyncfunction/prototype/index.html +++ /dev/null @@ -1,55 +0,0 @@ ---- -title: AsyncFunction.prototype -slug: Web/JavaScript/Reference/Global_Objects/AsyncFunction/prototype -translation_of: Web/JavaScript/Reference/Global_Objects/AsyncFunction/prototype ---- -
{{JSRef}}
- -

A propriedade AsyncFunction.prototype representa o objecto prototype {{jsxref("AsyncFunction")}}.

- -

Description

- -

Os objectos {{jsxref("AsyncFunction")}} são herdados de AsyncFunction.prototype e não podem ser modificados.

- -

Propriedades

- -
-
AsyncFunction.constructor
-
O valor inicial é {{jsxref("AsyncFunction")}}.
-
AsyncFunction.prototype[@@toStringTag]
-
Retorna "AsyncFunction".
-
- -

Especificações

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-async-function-constructor-prototype', 'AsyncFunction.prototype')}}{{Spec2('ESDraft')}}Definição inicial ES2017.
- -

Compatibilidade entre navegadores

- -
- - -

{{Compat("javascript.builtins.AsyncFunction.prototype")}}

-
- -

Ver também

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/number/prototype/index.html b/files/pt-pt/web/javascript/reference/global_objects/number/prototype/index.html deleted file mode 100644 index 9014ecdb24..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/number/prototype/index.html +++ /dev/null @@ -1,131 +0,0 @@ ---- -title: Number.prototype -slug: Web/JavaScript/Reference/Global_Objects/Number/prototype -tags: - - JavaScript - - Number - - Property - - Prototype -translation_of: Web/JavaScript/Reference/Global_Objects/Number -translation_of_original: Web/JavaScript/Reference/Global_Objects/Number/prototype ---- -
{{JSRef}}
- -

A propriedade Number.prototype representa o protótipo (prototype) para o constructor de {{jsxref("Number")}}.

- -
{{js_property_attributes(0, 0, 0)}}
- -

Descrição

- -

Todas as instâncias de {{jsxref("Number")}} herdam de Number.prototype. O objecto protótipo (prototype) do constructor de {{jsxref("Number")}} pode ser modificado para afectar todas as instâncias de {{jsxref( "Number")}}.

- -

Propriedades

- -
-
Number.prototype.constructor
-
Retorna a função criadora das instâncias deste objecto. Por predifinição este é o objecto {{jsxref("Number")}}.
-
- -

Métodos

- -
-
{{jsxref("Number.prototype.toExponential()")}}
-
Retorna uma representação em string do número em notação científica.
-
{{jsxref("Number.prototype.toFixed()")}}
-
Retorna uma representação em string do número em notação de ponto fixo.
-
{{jsxref("Number.prototype.toLocaleString()")}}
-
Retorna uma string do número numa representação sensível à linguagem. Faz override do método {{jsxref("Object.prototype.toLocaleString()")}}.
-
{{jsxref("Number.prototype.toPrecision()")}}
-
Retorna uma representação em string do número numa precisão especificada em ponto fixo ou notação científica.
-
{{jsxref("Number.prototype.toSource()")}} {{non-standard_inline}}
-
Retorna um objecto literal representando o objecto {{jsxref("Number")}} especificado; podes usar este valor para criar um novo objecto. Faz override ao método {{jsxref("Object.prototype.toSource()")}}.
-
{{jsxref("Number.prototype.toString()")}}
-
Retorna uma representação em string do objecto especificado na base especificada. Faz override ao método {{jsxref("Object.prototype.toString()")}}.
-
{{jsxref("Number.prototype.valueOf()")}}
-
Retorna o valor primitivo do objecto especificado. Faz override ao método {{jsxref("Object.prototype.valueOf()")}}.
-
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Definição Inicial. Implementado em  JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.7.4', 'Number')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-properties-of-the-number-prototype-object', 'Number')}}{{Spec2('ES6')}} 
- -

Compatibilidade dos browsers

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FuncionalidadeChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FuncionalidadeAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Ver também

- - diff --git a/files/pt-pt/web/javascript/reference/global_objects/object/prototype/index.html b/files/pt-pt/web/javascript/reference/global_objects/object/prototype/index.html deleted file mode 100644 index 411832665a..0000000000 --- a/files/pt-pt/web/javascript/reference/global_objects/object/prototype/index.html +++ /dev/null @@ -1,199 +0,0 @@ ---- -title: Object.prototype -slug: Web/JavaScript/Reference/Global_Objects/Object/prototype -tags: - - JavaScript - - Object - - Objeto - - Propriedade -translation_of: Web/JavaScript/Reference/Global_Objects/Object -translation_of_original: Web/JavaScript/Reference/Global_Objects/Object/prototype ---- -
{{JSRef}}
- -

A propriedade Object.prototype representa o prototype object {{jsxref("Object","Objeto")}} .

- -
{{js_property_attributes(0, 0, 0)}}
- -

Descrição

- -

Nearly all objects in JavaScript are instances of {{jsxref("Object")}}; a typical object inherits properties (including methods) from Object.prototype, although these properties may be shadowed (a.k.a. overridden). However, an Object may be deliberately created for which this is not true (e.g. by {{jsxref("Object.create", "Object.create(null)")}}), or it may be altered so that this is no longer true (e.g. with {{jsxref("Object.setPrototypeOf")}}).

- -

Changes to the Object prototype object are seen by all objects through prototype chaining, unless the properties and methods subject to those changes are overridden further along the prototype chain.  This provides a very powerful although potentially dangerous mechanism to override or extend object behavior.

- -

Propriedades

- -
-
{{jsxref("Object.prototype.constructor")}}
-
Specifies the function that creates an object's prototype.
-
{{jsxref("Object.prototype.__proto__")}} {{non-standard_inline}}
-
Points to the object which was used as prototype when the object was instantiated.
-
{{jsxref("Object.prototype.__noSuchMethod__")}} {{non-standard_inline}}
-
Allows a function to be defined that will be executed when an undefined object member is called as a method.
-
{{jsxref("Object.prototype.count","Object.prototype.__count__")}} {{obsolete_inline}}
-
Used to return the number of enumerable properties directly on a user-defined object, but has been removed.
-
{{jsxref("Object.prototype.parent","Object.prototype.__parent__")}} {{obsolete_inline}}
-
Used to point to an object's context, but has been removed.
-
- -

Métodos

- -
-
{{jsxref("Object.prototype.__defineGetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
-
Associates a function with a property that, when accessed, executes that function and returns its return value.
-
{{jsxref("Object.prototype.__defineSetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
-
Associates a function with a property that, when set, executes that function which modifies the property.
-
{{jsxref("Object.prototype.__lookupGetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
-
Returns the function associated with the specified property by the {{jsxref("Object.prototype.__defineGetter__()", "__defineGetter__()")}} method.
-
{{jsxref("Object.prototype.__lookupSetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
-
Returns the function associated with the specified property by the {{jsxref("Object.prototype.__defineSetter__()", "__defineSetter__()")}} method.
-
{{jsxref("Object.prototype.hasOwnProperty()")}}
-
Returns a boolean indicating whether an object contains the specified property as a direct property of that object and not inherited through the prototype chain.
-
{{jsxref("Object.prototype.isPrototypeOf()")}}
-
Returns a boolean indicating whether the object this method is called upon is in the prototype chain of the specified object.
-
{{jsxref("Object.prototype.propertyIsEnumerable()")}}
-
Returns a boolean indicating if the internal ECMAScript [[Enumerable]] attribute is set.
-
{{jsxref("Object.prototype.toSource()")}} {{non-standard_inline}}
-
Returns string containing the source of an object literal representing the object that this method is called upon; you can use this value to create a new object.
-
{{jsxref("Object.prototype.toLocaleString()")}}
-
Calls {{jsxref("Object.toString", "toString()")}}.
-
{{jsxref("Object.prototype.toString()")}}
-
Returns a string representation of the object.
-
{{jsxref("Object.prototype.unwatch()")}} {{non-standard_inline}}
-
Removes a watchpoint from a property of the object.
-
{{jsxref("Object.prototype.valueOf()")}}
-
Returns the primitive value of the specified object.
-
{{jsxref("Object.prototype.watch()")}} {{non-standard_inline}}
-
Adds a watchpoint to a property of the object.
-
{{jsxref("Object.prototype.eval()")}} {{obsolete_inline}}
-
Used to evaluate a string of JavaScript code in the context of the specified object, but has been removed.
-
- -

Exemplos

- -

When altering the behavior of existing Object.prototype methods, consider injecting code by wrapping your extension before or after the existing logic.  For example, this (untested) code will pre-conditionally execute custom logic before the built-in logic or someone else's extension is executed.

- -

When a function is called, the arguments to the call are held in the array-like "variable" arguments. For example, in the call "myFn(a, b, c)", the arguments within myFn's body will contain 3 array-like elements corresponding to (a, b, c).  When modifying prototypes with hooks, simply pass this & the arguments (the call state) to the current behavior by calling apply() on the function.  This pattern can be used for any prototype, such as Node.prototype, Function.prototype, etc.

- -
var current = Object.prototype.valueOf;
-
-// Since my property "-prop-value" is cross-cutting and isn't always
-// on the same prototype chain, I want to modify Object.prototype:
-Object.prototype.valueOf = function() {
-  if (this.hasOwnProperty('-prop-value')) {
-    return this['-prop-value'];
-  } else {
-    // It doesn't look like one of my objects, so let's fall back on
-    // the default behavior by reproducing the current behavior as best we can.
-    // The apply behaves like "super" in some other languages.
-    // Even though valueOf() doesn't take arguments, some other hook may.
-    return current.apply(this, arguments);
-  }
-}
-
- -

Since JavaScript doesn't exactly have sub-class objects, prototype is a useful workaround to make a “base class” object of certain functions that act as objects. For example:

- -
var Person = function(name) {
-  this.name = name;
-  this.canTalk = true;
-};
-
-Person.prototype.greet = function() {
-  if (this.canTalk) {
-    console.log('Hi, I am ' + this.name);
-  }
-};
-
-var Employee = function(name, title) {
-  Person.call(this, name);
-  this.title = title;
-};
-
-Employee.prototype = Object.create(Person.prototype);
-
-Employee.prototype.greet = function() {
-  if (this.canTalk) {
-    console.log('Hi, I am ' + this.name + ', the ' + this.title);
-  }
-};
-
-var Customer = function(name) {
-  Person.call(this, name);
-};
-
-Customer.prototype = Object.create(Person.prototype);
-
-var Mime = function(name) {
-  Person.call(this, name);
-  this.canTalk = false;
-};
-
-Mime.prototype = Object.create(Person.prototype);
-
-var bob = new Employee('Bob', 'Builder');
-var joe = new Customer('Joe');
-var rg = new Employee('Red Green', 'Handyman');
-var mike = new Customer('Mike');
-var mime = new Mime('Mime');
-
-bob.greet();
-// Hi, I am Bob, the Builder
-
-joe.greet();
-// Hi, I am Joe
-
-rg.greet();
-// Hi, I am Red Green, the Handyman
-
-mike.greet();
-// Hi, I am Mike
-
-mime.greet();
-
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.2.3.1', 'Object.prototype')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object.prototype', 'Object.prototype')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.prototype', 'Object.prototype')}}{{Spec2('ESDraft')}} 
- -

Compatibilidade de navegador

- -
- - -

{{Compat("javascript.builtins.Object.prototype")}}

-
- -

Consultar também

- - diff --git "a/files/pt-pt/web/javascript/reference/operadores/fun\303\247\303\243o/index.html" "b/files/pt-pt/web/javascript/reference/operadores/fun\303\247\303\243o/index.html" deleted file mode 100644 index 450183b727..0000000000 --- "a/files/pt-pt/web/javascript/reference/operadores/fun\303\247\303\243o/index.html" +++ /dev/null @@ -1,139 +0,0 @@ ---- -title: Expressão função (Function expression) -slug: Web/JavaScript/Reference/Operadores/função -tags: - - Expressões Primárias - - Funiconaldiade de Linguagem - - Função - - JavaScript - - Operador -translation_of: Web/JavaScript/Reference/Operators/function ---- -
{{jsSidebar("Operators")}}
- -

A palavra-chave function  pode ser utilziada para definir uma função dentro de uma expressão.

- -

You can also define functions using the Function constructor and a function declaration.

- -
{{EmbedInteractiveExample("pages/js/expressions-functionexpression.html", "shorter")}}
- - - -

Sintaxe

- -
let myFunction = function [name]([param1[, param2[, ..., paramN]]]) {
-   statements
-};
- -

As of ES2015, you can also use {{jsxref("Functions/Arrow_functions", "arrow functions")}}.

- -

Parâmetros

- -
-
name {{optional_inline}}
-
The function name. Can be omitted, in which case the function is anonymous. The name is only local to the function body.
-
paramN {{optional_inline}}
-
The name of an argument to be passed to the function.
-
statements {{optional_inline}}
-
The statements which comprise the body of the function.
-
- -

Descrição

- -

A function expression is very similar to and has almost the same syntax as a function declaration (see {{jsxref("Statements/function", "function statement")}} for details). The main difference between a function expression and a function declaration is the function name, which can be omitted in function expressions to create anonymous functions. A function expression can be used as an IIFE (Immediately Invoked Function Expression) which runs as soon as it is defined. See also the chapter about {{jsxref("Functions", "functions")}} for more information.

- -

Function expression hoisting

- -

Function expressions in JavaScript are not hoisted, unlike {{jsxref("Statements/function", "function declarations", "#Function_declaration_hoisting")}}. You can't use function expressions before you define them:

- -
console.log(notHoisted) // undefined
-//  even though the variable name is hoisted, the definition isn't. so it's undefined.
-notHoisted(); // TypeError: notHoisted is not a function
-
-var notHoisted = function() {
-   console.log('bar');
-};
-
- -

Named function expression

- -

If you want to refer to the current function inside the function body, you need to create a named function expression. This name is then local only to the function body (scope). This also avoids using the non-standard {{jsxref("Functions/arguments/callee", "arguments.callee")}} property.

- -
let math = {
-  'factit': function factorial(n) {
-    console.log(n)
-    if (n <= 1) {
-      return 1;
-    }
-    return n * factorial(n - 1);
-  }
-};
-
-math.factit(3) //3;2;1;
-
- -

The variable the function expression is assigned to will have a name property. The name doesn't change if it's assigned to a different variable. If function name is omitted, it will be the variable name (implicit name). If function name is present, it will be the function name (explicit name). This also applies to {{jsxref("Functions/Arrow_functions", "arrow functions")}} (arrows don't have a name so you can only give the variable an implicit name).

- -
var foo = function() {}
-foo.name // "foo"
-
-var foo2 = foo
-foo2.name // "foo"
-
-var bar = function baz() {}
-bar.name // "baz"
-
-console.log(foo === foo2); // true
-console.log(typeof baz); // undefined
-console.log(bar === baz); // false (errors because baz == undefined)
-
- -

Exemplos

- -

The following example defines an unnamed function and assigns it to x. The function returns the square of its argument:

- -
var x = function(y) {
-   return y * y;
-};
-
- -

More commonly it is used as a callback:

- -
button.addEventListener('click', function(event) {
-    console.log('button is clicked!')
-})
- -

Especificações

- - - - - - - - - - - - -
Especificação
{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}
- -

Compatibilidade de navegador

- - - -

{{Compat("javascript.operators.function")}}

- -

Consulte também 

- - diff --git a/files/pt-pt/web/javascript/reference/operadores/index.html b/files/pt-pt/web/javascript/reference/operadores/index.html deleted file mode 100644 index 02a550b7b0..0000000000 --- a/files/pt-pt/web/javascript/reference/operadores/index.html +++ /dev/null @@ -1,309 +0,0 @@ ---- -title: Expressões e operadores -slug: Web/JavaScript/Reference/Operadores -tags: - - JavaScript - - Operadores - - Página Landing - - Resumo - - Sinopse -translation_of: Web/JavaScript/Reference/Operators ---- -
{{jsSidebar("Operators")}}
- -

Este capítulo documenta todos os operadores, expressões e palavras-chave da linguagem JavaScript.

- -

Expressões e operadores por categoria

- -

For an alphabetical listing see the sidebar on the left.

- -

Expressões primárias

- -

Basic keywords and general expressions in JavaScript.

- -
-
{{JSxRef("Operators/this", "this")}}
-
The this keyword refers to a special property of an execution context.
-
{{JSxRef("Operators/function", "function")}}
-
The function keyword defines a function expression.
-
{{JSxRef("Operators/class", "class")}}
-
The class keyword defines a class expression.
-
{{JSxRef("Operators/function*", "function*")}}
-
The function* keyword defines a generator function expression.
-
{{JSxRef("Operators/yield", "yield")}}
-
Pause and resume a generator function.
-
{{JSxRef("Operators/yield*", "yield*")}}
-
Delegate to another generator function or iterable object.
-
{{JSxRef("Operators/async_function", "async function")}}
-
The async function defines an async function expression.
-
{{JSxRef("Operators/await", "await")}}
-
Pause and resume an async function and wait for the promise's resolution/rejection.
-
{{JSxRef("Global_Objects/Array", "[]")}}
-
Array initializer/literal syntax.
-
{{JSxRef("Operators/Object_initializer", "{}")}}
-
Object initializer/literal syntax.
-
{{JSxRef("Global_Objects/RegExp", "/ab+c/i")}}
-
Regular expression literal syntax.
-
{{JSxRef("Operators/Grouping", "( )")}}
-
Grouping operator.
-
- -

Expressões "Left-hand-side"

- -

Left values are the destination of an assignment.

- -
-
{{jsxref("Operators/Property_accessors", "Property accessors", "", 1)}}
-
Member operators provide access to a property or method of an object
- (object.property and object["property"]).
-
{{jsxref("Operators/new", "new")}}
-
The new operator creates an instance of a constructor.
-
new.target
-
In constructors, new.target refers to the constructor that was invoked by {{jsxref("Operators/new", "new")}}.
-
{{jsxref("Operators/super", "super")}}
-
The super keyword calls the parent constructor.
-
{{jsxref("Operators/Spread_operator", "...obj")}}
-
The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.
-
- -

Aumento e diminuição

- -

Postfix/prefix increment and postfix/prefix decrement operators.

- -
-
{{jsxref("Operators/Arithmetic_Operators", "A++", "#Increment")}}
-
Postfix increment operator.
-
{{jsxref("Operators/Arithmetic_Operators", "A--", "#Decrement")}}
-
Postfix decrement operator.
-
{{jsxref("Operators/Arithmetic_Operators", "++A", "#Increment")}}
-
Prefix increment operator.
-
{{jsxref("Operators/Arithmetic_Operators", "--A", "#Decrement")}}
-
Prefix decrement operator.
-
- -

Operadores unários

- -

A unary operation is operation with only one operand.

- -
-
{{jsxref("Operators/delete", "delete")}}
-
The delete operator deletes a property from an object.
-
{{jsxref("Operators/void", "void")}}
-
The void operator discards an expression's return value.
-
{{jsxref("Operators/typeof", "typeof")}}
-
The typeof operator determines the type of a given object.
-
{{jsxref("Operators/Arithmetic_Operators", "+", "#Unary_plus")}}
-
The unary plus operator converts its operand to Number type.
-
{{jsxref("Operators/Arithmetic_Operators", "-", "#Unary_negation")}}
-
The unary negation operator converts its operand to Number type and then negates it.
-
{{jsxref("Operators/Bitwise_Operators", "~", "#Bitwise_NOT")}}
-
Bitwise NOT operator.
-
{{jsxref("Operators/Logical_Operators", "!", "#Logical_NOT")}}
-
Logical NOT operator.
-
- -

Operadores de aritmética

- -

Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value.

- -
-
{{jsxref("Operators/Arithmetic_Operators", "+", "#Addition")}}
-
Addition operator.
-
{{jsxref("Operators/Arithmetic_Operators", "-", "#Subtraction")}}
-
Subtraction operator.
-
{{jsxref("Operators/Arithmetic_Operators", "/", "#Division")}}
-
Division operator.
-
{{jsxref("Operators/Arithmetic_Operators", "*", "#Multiplication")}}
-
Multiplication operator.
-
{{jsxref("Operators/Arithmetic_Operators", "%", "#Remainder")}}
-
Remainder operator.
-
- -
-
{{JSxRef("Operators/Arithmetic_Operators", "**", "#Exponentiation")}}
-
Exponentiation operator.
-
- -

Operadores relacionais

- -

A comparison operator compares its operands and returns a Boolean value based on whether the comparison is true.

- -
-
{{jsxref("Operators/in", "in")}}
-
The in operator determines whether an object has a given property.
-
{{jsxref("Operators/instanceof", "instanceof")}}
-
The instanceof operator determines whether an object is an instance of another object.
-
{{jsxref("Operators/Comparison_Operators", "<", "#Less_than_operator")}}
-
Less than operator.
-
{{jsxref("Operators/Comparison_Operators", ">", "#Greater_than_operator")}}
-
Greater than operator.
-
{{jsxref("Operators/Comparison_Operators", "<=", "#Less_than_or_equal_operator")}}
-
Less than or equal operator.
-
{{jsxref("Operators/Comparison_Operators", ">=", "#Greater_than_or_equal_operator")}}
-
Greater than or equal operator.
-
- -
-

Nota: => não é um operador, mas a notação para funções seta (arrow).

-
- -

Operadores de equality

- -

The result of evaluating an equality operator is always of type Boolean based on whether the comparison is true.

- -
-
{{jsxref("Operators/Comparison_Operators", "==", "#Equality")}}
-
Equality operator.
-
{{jsxref("Operators/Comparison_Operators", "!=", "#Inequality")}}
-
Inequality operator.
-
{{jsxref("Operators/Comparison_Operators", "===", "#Identity")}}
-
Identity operator.
-
{{jsxref("Operators/Comparison_Operators", "!==", "#Nonidentity")}}
-
Nonidentity operator.
-
- -

Bitwise shift operators

- -

Operations to shift all bits of the operand.

- -
-
{{jsxref("Operators/Bitwise_Operators", "<<", "#Left_shift")}}
-
Bitwise left shift operator.
-
{{jsxref("Operators/Bitwise_Operators", ">>", "#Right_shift")}}
-
Bitwise right shift operator.
-
{{jsxref("Operators/Bitwise_Operators", ">>>", "#Unsigned_right_shift")}}
-
Bitwise unsigned right shift operator.
-
- -

Operadores de binário bitwise

- -

Bitwise operators treat their operands as a set of 32 bits (zeros and ones) and return standard JavaScript numerical values.

- -
-
{{jsxref("Operators/Bitwise_Operators", "&", "#Bitwise_AND")}}
-
Bitwise AND.
-
{{jsxref("Operators/Bitwise_Operators", "|", "#Bitwise_OR")}}
-
Bitwise OR.
-
{{jsxref("Operators/Bitwise_Operators", "^", "#Bitwise_XOR")}}
-
Bitwise XOR.
-
- -

Operadores de binário logical

- -

Logical operators are typically used with boolean (logical) values, and when they are, they return a boolean value.

- -
-
{{jsxref("Operators/Logical_Operators", "&&", "#Logical_AND")}}
-
Logical AND.
-
{{jsxref("Operators/Logical_Operators", "||", "#Logical_OR")}}
-
Logical OR.
-
- -

Operdor condicional (ternário)

- -
-
{{jsxref("Operators/Conditional_Operator", "(condition ? ifTrue : ifFalse)")}}
-
-

The conditional operator returns one of two values based on the logical value of the condition.

-
-
- -

Operadores de Assignment

- -

An assignment operator assigns a value to its left operand based on the value of its right operand.

- -
-
{{jsxref("Operators/Assignment_Operators", "=", "#Assignment")}}
-
Assignment operator.
-
{{jsxref("Operators/Assignment_Operators", "*=", "#Multiplication_assignment")}}
-
Multiplication assignment.
-
{{jsxref("Operators/Assignment_Operators", "/=", "#Division_assignment")}}
-
Division assignment.
-
{{jsxref("Operators/Assignment_Operators", "%=", "#Remainder_assignment")}}
-
Remainder assignment.
-
{{jsxref("Operators/Assignment_Operators", "+=", "#Addition_assignment")}}
-
Addition assignment.
-
{{jsxref("Operators/Assignment_Operators", "-=", "#Subtraction_assignment")}}
-
Subtraction assignment
-
{{jsxref("Operators/Assignment_Operators", "<<=", "#Left_shift_assignment")}}
-
Left shift assignment.
-
{{jsxref("Operators/Assignment_Operators", ">>=", "#Right_shift_assignment")}}
-
Right shift assignment.
-
{{jsxref("Operators/Assignment_Operators", ">>>=", "#Unsigned_right_shift_assignment")}}
-
Unsigned right shift assignment.
-
{{jsxref("Operators/Assignment_Operators", "&=", "#Bitwise_AND_assignment")}}
-
Bitwise AND assignment.
-
{{jsxref("Operators/Assignment_Operators", "^=", "#Bitwise_XOR_assignment")}}
-
Bitwise XOR assignment.
-
{{jsxref("Operators/Assignment_Operators", "|=", "#Bitwise_OR_assignment")}}
-
Bitwise OR assignment.
-
{{jsxref("Operators/Destructuring_assignment", "[a, b] = [1, 2]")}}
- {{jsxref("Operators/Destructuring_assignment", "{a, b} = {a:1, b:2}")}}
-
-

Destructuring assignment allows you to assign the properties of an array or object to variables using syntax that looks similar to array or object literals.

-
-
- -

Operador de aspas

- -
-
{{jsxref("Operators/Comma_Operator", ",")}}
-
The comma operator allows multiple expressions to be evaluated in a single statement and returns the result of the last expression.
-
- -

Funcionalidades não padrão

- -
-
{{non-standard_inline}} {{jsxref("Operators/Legacy_generator_function", "Legacy generator function", "", 1)}}
-
The function keyword can be used to define a legacy generator function inside an expression. To make the function a legacy generator, the function body should contains at least one {{jsxref("Operators/yield", "yield")}} expression.
-
{{non-standard_inline}} {{jsxref("Operators/Expression_closures", "Expression closures", "", 1)}}
-
The expression closure syntax is a shorthand for writing simple function.
-
{{non-standard_inline}} {{jsxref("Operators/Array_comprehensions", "[for (x of y) x]")}}
-
Array comprehensions.
-
{{non-standard_inline}} {{jsxref("Operators/Generator_comprehensions", "(for (x of y) y)")}}
-
Generator comprehensions.
-
- -

Especificações

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
EspecificaçãoEstadoComentário
{{SpecName('ES1', '#sec-11', 'Expressions')}}{{Spec2('ES1')}}Initial definition
{{SpecName('ES5.1', '#sec-11', 'Expressions')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}{{Spec2('ES6')}}New: Spread operator, destructuring assignment, super keyword.
{{SpecName('ESDraft', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}{{Spec2('ESDraft')}}
- -

Compatibilidade de navegador

- - - -

{{Compat("javascript.operators")}}

- -

Consulte também

- - diff --git a/files/pt-pt/web/javascript/reference/operadores/operador_virgula/index.html b/files/pt-pt/web/javascript/reference/operadores/operador_virgula/index.html deleted file mode 100644 index e797f92953..0000000000 --- a/files/pt-pt/web/javascript/reference/operadores/operador_virgula/index.html +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: Operador Vírgula -slug: Web/JavaScript/Reference/Operadores/Operador_virgula -tags: - - Composto - - Expressão - - Funcionalidade de Linguagem - - JavaScript - - Operador - - Referencia - - Vírgula -translation_of: Web/JavaScript/Reference/Operators/Comma_Operator ---- -
Operador {{jsSidebar("Operators")}}
- -

operador vírgula (,) avalia cada um dos seus operandos (da esquerda para a direita) e devolve o valor do último operando. This lets you create a compound expression in which multiple expressions are evaluated, with the compound expression's final value being the value of the rightmost of its member expressions. This is commonly used to provide multiple parameters to a for loop.

- -
{{EmbedInteractiveExample("pages/js/expressions-commaoperators.html")}}
- - - -

Sintaxe

- -
expr1, expr2, expr3...
- -

Parâmetros

- -
-
expr1, expr2, expr3...
-
One or more expressions, the last of which is returned as the value of the compound expression.
-
- -

Notas de utilização

- -

You can use the comma operator when you want to include multiple expressions in a location that requires a single expression. The most common usage of this operator is to supply multiple parameters in a for loop.

- -

The comma operator is fully different from the comma within arrays, objects, and function arguments and parameters.

- -

Exemplos

- -

If a is a 2-dimensional array with 10 elements on each side, the following code uses the comma operator to increment i and decrement j at once.

- -

The following code prints the values of the diagonal elements in the array:

- -
for (var i = 0, j = 9; i <= 9; i++, j--)
-  console.log('a[' + i + '][' + j + '] = ' + a[i][j]);
- -

Note that the comma operators in assignments may appear not to have the normal effect of comma operators because they don't exist within an expression. In the following example, a is set to the value of b = 3 (which is 3), but the c = 4 expression still evaluates and its result returned to console (i.e., 4). This is due to operator precedence and associativity.

- -
var a, b, c;
-
-a = b = 3, c = 4; // Returns 4 in console
-console.log(a); // 3 (left-most)
-
-var x, y, z;
-
-x = (y = 5, z = 6); // Returns 6 in console
-console.log(x); // 6 (right-most)
-
- -

Processing and then returning

- -

Another example that one could make with comma operator is processing before returning. As stated, only the last element will be returned but all others are going to be evaluated as well. So, one could do:

- -
function myFunc() {
-  var x = 0;
-
-  return (x += 1, x); // the same as return ++x;
-}
- -

Especificações

- - - - - - - - - - -
Especificação
{{SpecName('ESDraft', '#sec-comma-operator', 'Comma operator')}}
- -

Compatibilidade de navegador

- - - -

{{Compat("javascript.operators.comma")}}

- -

Consulte também

- - diff --git a/files/pt-pt/web/javascript/reference/operadores/precedencia_operador/index.html b/files/pt-pt/web/javascript/reference/operadores/precedencia_operador/index.html deleted file mode 100644 index 03d4345410..0000000000 --- a/files/pt-pt/web/javascript/reference/operadores/precedencia_operador/index.html +++ /dev/null @@ -1,461 +0,0 @@ ---- -title: Precedência de operador -slug: Web/JavaScript/Reference/Operadores/Precedencia_operador -tags: - - Guía - - JavaScript - - precedência -translation_of: Web/JavaScript/Reference/Operators/Operator_Precedence ---- -
{{jsSidebar("Operators")}}
- -

A precedência de operador determina a maneira pela qual os operadores são analisados ​​em relação a cada um. Os operadores com maior precedência tornam-se operandos dos operadores com menor precedência..

- -
{{EmbedInteractiveExample("pages/js/expressions-operatorprecedence.html")}}
- - - -

Precedência e Associabilidade

- -

Consider an expression describable by the representation below. Note that both OP1 and OPare fill-in-the-blanks for OPerators.

- -
a OP b OP c
-
- -

If OP1 and OP2 have different precedence levels (see the table below), the operator with the highest precedence goes first and associativity does not matter. Observe how multiplication has higher associativity than addition and executed first, even though addition is written first in the code.

- -
console.log(3 + 10 * 2);   // logs 23
-console.log(3 + (10 * 2)); // logs 23 because parentheses here are superfluous
-console.log((3 + 10) * 2); // logs 26 because the parentheses change the order 
- -

Left-associativity (left-to-right) means that it is processed as (a OP1 b) OP2 c, while right-associativity (right-to-left) means it is interpreted as a OP1 (b OP2 c). Assignment operators are right-associative, so you can write:

- -
a = b = 5; // same as writing a = (b = 5);
-
- -

with the expected result that a and b get the value 5. This is because the assignment operator returns the value that is assigned. First, b is set to 5. Then the a is also set to 5, the return value of b = 5, aka right operand of the assignment.

- -

As another example, the unique exponentiation operator has right-associativity, whereas other arithmetic operators have left-associativity. It is interesting to note that, the order of evaluation is always left-to-right irregardless of associativity.

- - - - - - - - - - - - - - - - -
CódigoResultado
-
-function echo(name, num) {
-    console.log("Evaluating the " + name + " side");
-    return num;
-}
-// Notice the division operator (/)
-console.log(echo("left", 6) / echo("right", 2));
-
-
-
-Evaluating the left side
-Evaluating the right side
-3
-
-
-
-function echo(name, num) {
-    console.log("Evaluating the " + name + " side");
-    return num;
-}
-// Notice the exponentiation operator (**)
-console.log(echo("left", 2) ** echo("right", 3));
-
-
-Evaluating the left side
-Evaluating the right side
-8
-
- -

The difference in associativity comes into play when there are multiple operators of the same precedence. With only one operator or operators of different precedences, associativity does affect the output, as seen in the example above. In the example below, observe how associativity affects the output when multiple of the same operator are used.

- - - - - - - - - - - - - - - - - - - - -
CódigoResultado
-
-function echo(name, num) {
-    console.log("Evaluating the " + name + " side");
-    return num;
-}
-// Notice the division operator (/)
-console.log(echo("left", 6) / echo("middle", 2) / echo("right", 3));
-
-
-
-Evaluating the left side
-Evaluating the middle side
-Evaluating the right side
-1
-
-
-
-function echo(name, num) {
-    console.log("Evaluating the " + name + " side");
-    return num;
-}
-// Notice the exponentiation operator (**)
-console.log(echo("left", 2) ** echo("middle", 3) ** echo("right", 2));
-
-
-
-Evaluating the left side
-Evaluating the middle side
-Evaluating the right side
-512
-
-
-
-function echo(name, num) {
-    console.log("Evaluating the " + name + " side");
-    return num;
-}
-// Notice the parentheses around the left and middle exponentiation
-console.log((echo("left", 2) ** echo("middle", 3)) ** echo("right", 2));
-
-
-Evaluating the left side
-Evaluating the middle side
-Evaluating the right side
-64
-
- -

Looking at the code snippets above, 6 / 3 / 2 is the same as (6 / 3) / 2 because division is left-associative. Exponentiation, on the other hand, is right-associative, so 2 ** 3 ** 2 is the same as 2 ** (3 ** 2). Thus, doing (2 ** 3) ** 2 changes the order and results in the 64 seen in the table above.

- -

Remember that precedence comes before associativity. So, mixing division and exponentiation, the exponentiation comes before the division. For example, 2 ** 3 / 3 ** 2 results in 0.8888888888888888 because it is the same as (2 ** 3) / (3 ** 2).

- -

Note on Grouping and Short-Circuiting

- -

In the table below, Grouping is listed as having the highest precedence. However, that does not always mean the expression within the grouping symbols ( … ) is evaluated first, especially when it comes to short-circuiting.

- -

Short-circuiting is jargon for conditional evaluation. For example, in the expression a && (b + c), if a is “falsy”, then the sub-expression (b + c) will not even get evaluated, even if it is in parentheses. We could say that the logical disjunction operator (“OR”) is “short-circuited”. Along with logical disjunction, other short-circuited operators include logical conjunction (“AND”), nullish-coalescing, optional chaining, and the conditional operator. Some more examples follow.

- -
a || (b * c);  // evaluate `a` first, then produce `a` if `a` is “truthy”
-a && (b < c);  // evaluate `a` first, then produce `a` if `a` is “falsy”
-a ?? (b || c); // evaluate `a` first, then produce `a` if `a` is not `null` and not `undefined`
-a?.b.c;        // evaluate `a` first, then produce `a` if `a` is `null` or `undefined`
-
- -

Exemplos

- -
3 > 2 && 2 > 1
-// returns true
-
-3 > 2 > 1
-// Returns false because 3 > 2 is true, then true is converted to 1 in inequality operators, therefore true > 1 becomes 1 > 1, which
-//  is false. Adding parentheses makes things clear: (3 > 2) > 1.
-
-
- -

Tabela

- -

The following table is ordered from highest (20) to lowest (1) precedence.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PrecedênciaTipo de operador (Operator)AssociatividadeOperadores individuais
20{{jsxref("Operators/Grouping", "Grouping")}}n/a( … )
19{{jsxref("Operators/Property_Accessors", "Member Access", "#Dot_notation")}}left-to-right… . …
{{jsxref("Operators/Property_Accessors", "Computed Member Access","#Bracket_notation")}}left-to-right… [ … ]
{{jsxref("Operators/new","new")}} (with argument list)n/anew … ( … )
Function Callleft-to-right… ( … )
18{{jsxref("Operators/new","new")}} (without argument list)right-to-leftnew …
17{{jsxref("Operators/Arithmetic_Operators","Postfix Increment","#Increment")}}n/a… ++
{{jsxref("Operators/Arithmetic_Operators","Postfix Decrement","#Decrement")}}… --
16Logical NOTright-to-left! …
Bitwise NOT~ …
Unary Plus+ …
Unary Negation- …
Prefix Increment++ …
Prefix Decrement-- …
typeoftypeof …
voidvoid …
deletedelete …
awaitawait …
15Exponentiationright-to-left… ** …
14Multiplicationleft-to-right… * …
Division… / …
Remainder… % …
13Additionleft-to-right… + …
Subtraction… - …
12Bitwise Left Shiftleft-to-right… << …
Bitwise Right Shift… >> …
Bitwise Unsigned Right Shift… >>> …
11Less Thanleft-to-right… < …
Less Than Or Equal… <= …
Greater Than… > …
Greater Than Or Equal… >= …
in… in …
instanceof… instanceof …
10Equalityleft-to-right… == …
Inequality… != …
Strict Equality… === …
Strict Inequality… !== …
9Bitwise ANDleft-to-right… & …
8Bitwise XORleft-to-right… ^ …
7Bitwise ORleft-to-right… | …
6Logical ANDleft-to-right… && …
5Logical ORleft-to-right… || …
4Conditionalright-to-left… ? … : …
3Assignmentright-to-left… = …
… += …
… -= …
… **= …
… *= …
… /= …
… %= …
… <<= …
… >>= …
… >>>= …
… &= …
… ^= …
… |= …
2{{jsxref("Operators/yield", "yield")}}right-to-leftyield …
{{jsxref("Operators/yield*", "yield*")}}yield* …
1Vírgula / Sequêncialeft-to-right… , …
diff --git a/files/pt-pt/web/javascript/reference/operators/comma_operator/index.html b/files/pt-pt/web/javascript/reference/operators/comma_operator/index.html new file mode 100644 index 0000000000..e797f92953 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/operators/comma_operator/index.html @@ -0,0 +1,94 @@ +--- +title: Operador Vírgula +slug: Web/JavaScript/Reference/Operadores/Operador_virgula +tags: + - Composto + - Expressão + - Funcionalidade de Linguagem + - JavaScript + - Operador + - Referencia + - Vírgula +translation_of: Web/JavaScript/Reference/Operators/Comma_Operator +--- +
Operador {{jsSidebar("Operators")}}
+ +

operador vírgula (,) avalia cada um dos seus operandos (da esquerda para a direita) e devolve o valor do último operando. This lets you create a compound expression in which multiple expressions are evaluated, with the compound expression's final value being the value of the rightmost of its member expressions. This is commonly used to provide multiple parameters to a for loop.

+ +
{{EmbedInteractiveExample("pages/js/expressions-commaoperators.html")}}
+ + + +

Sintaxe

+ +
expr1, expr2, expr3...
+ +

Parâmetros

+ +
+
expr1, expr2, expr3...
+
One or more expressions, the last of which is returned as the value of the compound expression.
+
+ +

Notas de utilização

+ +

You can use the comma operator when you want to include multiple expressions in a location that requires a single expression. The most common usage of this operator is to supply multiple parameters in a for loop.

+ +

The comma operator is fully different from the comma within arrays, objects, and function arguments and parameters.

+ +

Exemplos

+ +

If a is a 2-dimensional array with 10 elements on each side, the following code uses the comma operator to increment i and decrement j at once.

+ +

The following code prints the values of the diagonal elements in the array:

+ +
for (var i = 0, j = 9; i <= 9; i++, j--)
+  console.log('a[' + i + '][' + j + '] = ' + a[i][j]);
+ +

Note that the comma operators in assignments may appear not to have the normal effect of comma operators because they don't exist within an expression. In the following example, a is set to the value of b = 3 (which is 3), but the c = 4 expression still evaluates and its result returned to console (i.e., 4). This is due to operator precedence and associativity.

+ +
var a, b, c;
+
+a = b = 3, c = 4; // Returns 4 in console
+console.log(a); // 3 (left-most)
+
+var x, y, z;
+
+x = (y = 5, z = 6); // Returns 6 in console
+console.log(x); // 6 (right-most)
+
+ +

Processing and then returning

+ +

Another example that one could make with comma operator is processing before returning. As stated, only the last element will be returned but all others are going to be evaluated as well. So, one could do:

+ +
function myFunc() {
+  var x = 0;
+
+  return (x += 1, x); // the same as return ++x;
+}
+ +

Especificações

+ + + + + + + + + + +
Especificação
{{SpecName('ESDraft', '#sec-comma-operator', 'Comma operator')}}
+ +

Compatibilidade de navegador

+ + + +

{{Compat("javascript.operators.comma")}}

+ +

Consulte também

+ + diff --git a/files/pt-pt/web/javascript/reference/operators/function/index.html b/files/pt-pt/web/javascript/reference/operators/function/index.html new file mode 100644 index 0000000000..450183b727 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/operators/function/index.html @@ -0,0 +1,139 @@ +--- +title: Expressão função (Function expression) +slug: Web/JavaScript/Reference/Operadores/função +tags: + - Expressões Primárias + - Funiconaldiade de Linguagem + - Função + - JavaScript + - Operador +translation_of: Web/JavaScript/Reference/Operators/function +--- +
{{jsSidebar("Operators")}}
+ +

A palavra-chave function  pode ser utilziada para definir uma função dentro de uma expressão.

+ +

You can also define functions using the Function constructor and a function declaration.

+ +
{{EmbedInteractiveExample("pages/js/expressions-functionexpression.html", "shorter")}}
+ + + +

Sintaxe

+ +
let myFunction = function [name]([param1[, param2[, ..., paramN]]]) {
+   statements
+};
+ +

As of ES2015, you can also use {{jsxref("Functions/Arrow_functions", "arrow functions")}}.

+ +

Parâmetros

+ +
+
name {{optional_inline}}
+
The function name. Can be omitted, in which case the function is anonymous. The name is only local to the function body.
+
paramN {{optional_inline}}
+
The name of an argument to be passed to the function.
+
statements {{optional_inline}}
+
The statements which comprise the body of the function.
+
+ +

Descrição

+ +

A function expression is very similar to and has almost the same syntax as a function declaration (see {{jsxref("Statements/function", "function statement")}} for details). The main difference between a function expression and a function declaration is the function name, which can be omitted in function expressions to create anonymous functions. A function expression can be used as an IIFE (Immediately Invoked Function Expression) which runs as soon as it is defined. See also the chapter about {{jsxref("Functions", "functions")}} for more information.

+ +

Function expression hoisting

+ +

Function expressions in JavaScript are not hoisted, unlike {{jsxref("Statements/function", "function declarations", "#Function_declaration_hoisting")}}. You can't use function expressions before you define them:

+ +
console.log(notHoisted) // undefined
+//  even though the variable name is hoisted, the definition isn't. so it's undefined.
+notHoisted(); // TypeError: notHoisted is not a function
+
+var notHoisted = function() {
+   console.log('bar');
+};
+
+ +

Named function expression

+ +

If you want to refer to the current function inside the function body, you need to create a named function expression. This name is then local only to the function body (scope). This also avoids using the non-standard {{jsxref("Functions/arguments/callee", "arguments.callee")}} property.

+ +
let math = {
+  'factit': function factorial(n) {
+    console.log(n)
+    if (n <= 1) {
+      return 1;
+    }
+    return n * factorial(n - 1);
+  }
+};
+
+math.factit(3) //3;2;1;
+
+ +

The variable the function expression is assigned to will have a name property. The name doesn't change if it's assigned to a different variable. If function name is omitted, it will be the variable name (implicit name). If function name is present, it will be the function name (explicit name). This also applies to {{jsxref("Functions/Arrow_functions", "arrow functions")}} (arrows don't have a name so you can only give the variable an implicit name).

+ +
var foo = function() {}
+foo.name // "foo"
+
+var foo2 = foo
+foo2.name // "foo"
+
+var bar = function baz() {}
+bar.name // "baz"
+
+console.log(foo === foo2); // true
+console.log(typeof baz); // undefined
+console.log(bar === baz); // false (errors because baz == undefined)
+
+ +

Exemplos

+ +

The following example defines an unnamed function and assigns it to x. The function returns the square of its argument:

+ +
var x = function(y) {
+   return y * y;
+};
+
+ +

More commonly it is used as a callback:

+ +
button.addEventListener('click', function(event) {
+    console.log('button is clicked!')
+})
+ +

Especificações

+ + + + + + + + + + + + +
Especificação
{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}
+ +

Compatibilidade de navegador

+ + + +

{{Compat("javascript.operators.function")}}

+ +

Consulte também 

+ + diff --git a/files/pt-pt/web/javascript/reference/operators/index.html b/files/pt-pt/web/javascript/reference/operators/index.html new file mode 100644 index 0000000000..02a550b7b0 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/operators/index.html @@ -0,0 +1,309 @@ +--- +title: Expressões e operadores +slug: Web/JavaScript/Reference/Operadores +tags: + - JavaScript + - Operadores + - Página Landing + - Resumo + - Sinopse +translation_of: Web/JavaScript/Reference/Operators +--- +
{{jsSidebar("Operators")}}
+ +

Este capítulo documenta todos os operadores, expressões e palavras-chave da linguagem JavaScript.

+ +

Expressões e operadores por categoria

+ +

For an alphabetical listing see the sidebar on the left.

+ +

Expressões primárias

+ +

Basic keywords and general expressions in JavaScript.

+ +
+
{{JSxRef("Operators/this", "this")}}
+
The this keyword refers to a special property of an execution context.
+
{{JSxRef("Operators/function", "function")}}
+
The function keyword defines a function expression.
+
{{JSxRef("Operators/class", "class")}}
+
The class keyword defines a class expression.
+
{{JSxRef("Operators/function*", "function*")}}
+
The function* keyword defines a generator function expression.
+
{{JSxRef("Operators/yield", "yield")}}
+
Pause and resume a generator function.
+
{{JSxRef("Operators/yield*", "yield*")}}
+
Delegate to another generator function or iterable object.
+
{{JSxRef("Operators/async_function", "async function")}}
+
The async function defines an async function expression.
+
{{JSxRef("Operators/await", "await")}}
+
Pause and resume an async function and wait for the promise's resolution/rejection.
+
{{JSxRef("Global_Objects/Array", "[]")}}
+
Array initializer/literal syntax.
+
{{JSxRef("Operators/Object_initializer", "{}")}}
+
Object initializer/literal syntax.
+
{{JSxRef("Global_Objects/RegExp", "/ab+c/i")}}
+
Regular expression literal syntax.
+
{{JSxRef("Operators/Grouping", "( )")}}
+
Grouping operator.
+
+ +

Expressões "Left-hand-side"

+ +

Left values are the destination of an assignment.

+ +
+
{{jsxref("Operators/Property_accessors", "Property accessors", "", 1)}}
+
Member operators provide access to a property or method of an object
+ (object.property and object["property"]).
+
{{jsxref("Operators/new", "new")}}
+
The new operator creates an instance of a constructor.
+
new.target
+
In constructors, new.target refers to the constructor that was invoked by {{jsxref("Operators/new", "new")}}.
+
{{jsxref("Operators/super", "super")}}
+
The super keyword calls the parent constructor.
+
{{jsxref("Operators/Spread_operator", "...obj")}}
+
The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.
+
+ +

Aumento e diminuição

+ +

Postfix/prefix increment and postfix/prefix decrement operators.

+ +
+
{{jsxref("Operators/Arithmetic_Operators", "A++", "#Increment")}}
+
Postfix increment operator.
+
{{jsxref("Operators/Arithmetic_Operators", "A--", "#Decrement")}}
+
Postfix decrement operator.
+
{{jsxref("Operators/Arithmetic_Operators", "++A", "#Increment")}}
+
Prefix increment operator.
+
{{jsxref("Operators/Arithmetic_Operators", "--A", "#Decrement")}}
+
Prefix decrement operator.
+
+ +

Operadores unários

+ +

A unary operation is operation with only one operand.

+ +
+
{{jsxref("Operators/delete", "delete")}}
+
The delete operator deletes a property from an object.
+
{{jsxref("Operators/void", "void")}}
+
The void operator discards an expression's return value.
+
{{jsxref("Operators/typeof", "typeof")}}
+
The typeof operator determines the type of a given object.
+
{{jsxref("Operators/Arithmetic_Operators", "+", "#Unary_plus")}}
+
The unary plus operator converts its operand to Number type.
+
{{jsxref("Operators/Arithmetic_Operators", "-", "#Unary_negation")}}
+
The unary negation operator converts its operand to Number type and then negates it.
+
{{jsxref("Operators/Bitwise_Operators", "~", "#Bitwise_NOT")}}
+
Bitwise NOT operator.
+
{{jsxref("Operators/Logical_Operators", "!", "#Logical_NOT")}}
+
Logical NOT operator.
+
+ +

Operadores de aritmética

+ +

Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value.

+ +
+
{{jsxref("Operators/Arithmetic_Operators", "+", "#Addition")}}
+
Addition operator.
+
{{jsxref("Operators/Arithmetic_Operators", "-", "#Subtraction")}}
+
Subtraction operator.
+
{{jsxref("Operators/Arithmetic_Operators", "/", "#Division")}}
+
Division operator.
+
{{jsxref("Operators/Arithmetic_Operators", "*", "#Multiplication")}}
+
Multiplication operator.
+
{{jsxref("Operators/Arithmetic_Operators", "%", "#Remainder")}}
+
Remainder operator.
+
+ +
+
{{JSxRef("Operators/Arithmetic_Operators", "**", "#Exponentiation")}}
+
Exponentiation operator.
+
+ +

Operadores relacionais

+ +

A comparison operator compares its operands and returns a Boolean value based on whether the comparison is true.

+ +
+
{{jsxref("Operators/in", "in")}}
+
The in operator determines whether an object has a given property.
+
{{jsxref("Operators/instanceof", "instanceof")}}
+
The instanceof operator determines whether an object is an instance of another object.
+
{{jsxref("Operators/Comparison_Operators", "<", "#Less_than_operator")}}
+
Less than operator.
+
{{jsxref("Operators/Comparison_Operators", ">", "#Greater_than_operator")}}
+
Greater than operator.
+
{{jsxref("Operators/Comparison_Operators", "<=", "#Less_than_or_equal_operator")}}
+
Less than or equal operator.
+
{{jsxref("Operators/Comparison_Operators", ">=", "#Greater_than_or_equal_operator")}}
+
Greater than or equal operator.
+
+ +
+

Nota: => não é um operador, mas a notação para funções seta (arrow).

+
+ +

Operadores de equality

+ +

The result of evaluating an equality operator is always of type Boolean based on whether the comparison is true.

+ +
+
{{jsxref("Operators/Comparison_Operators", "==", "#Equality")}}
+
Equality operator.
+
{{jsxref("Operators/Comparison_Operators", "!=", "#Inequality")}}
+
Inequality operator.
+
{{jsxref("Operators/Comparison_Operators", "===", "#Identity")}}
+
Identity operator.
+
{{jsxref("Operators/Comparison_Operators", "!==", "#Nonidentity")}}
+
Nonidentity operator.
+
+ +

Bitwise shift operators

+ +

Operations to shift all bits of the operand.

+ +
+
{{jsxref("Operators/Bitwise_Operators", "<<", "#Left_shift")}}
+
Bitwise left shift operator.
+
{{jsxref("Operators/Bitwise_Operators", ">>", "#Right_shift")}}
+
Bitwise right shift operator.
+
{{jsxref("Operators/Bitwise_Operators", ">>>", "#Unsigned_right_shift")}}
+
Bitwise unsigned right shift operator.
+
+ +

Operadores de binário bitwise

+ +

Bitwise operators treat their operands as a set of 32 bits (zeros and ones) and return standard JavaScript numerical values.

+ +
+
{{jsxref("Operators/Bitwise_Operators", "&", "#Bitwise_AND")}}
+
Bitwise AND.
+
{{jsxref("Operators/Bitwise_Operators", "|", "#Bitwise_OR")}}
+
Bitwise OR.
+
{{jsxref("Operators/Bitwise_Operators", "^", "#Bitwise_XOR")}}
+
Bitwise XOR.
+
+ +

Operadores de binário logical

+ +

Logical operators are typically used with boolean (logical) values, and when they are, they return a boolean value.

+ +
+
{{jsxref("Operators/Logical_Operators", "&&", "#Logical_AND")}}
+
Logical AND.
+
{{jsxref("Operators/Logical_Operators", "||", "#Logical_OR")}}
+
Logical OR.
+
+ +

Operdor condicional (ternário)

+ +
+
{{jsxref("Operators/Conditional_Operator", "(condition ? ifTrue : ifFalse)")}}
+
+

The conditional operator returns one of two values based on the logical value of the condition.

+
+
+ +

Operadores de Assignment

+ +

An assignment operator assigns a value to its left operand based on the value of its right operand.

+ +
+
{{jsxref("Operators/Assignment_Operators", "=", "#Assignment")}}
+
Assignment operator.
+
{{jsxref("Operators/Assignment_Operators", "*=", "#Multiplication_assignment")}}
+
Multiplication assignment.
+
{{jsxref("Operators/Assignment_Operators", "/=", "#Division_assignment")}}
+
Division assignment.
+
{{jsxref("Operators/Assignment_Operators", "%=", "#Remainder_assignment")}}
+
Remainder assignment.
+
{{jsxref("Operators/Assignment_Operators", "+=", "#Addition_assignment")}}
+
Addition assignment.
+
{{jsxref("Operators/Assignment_Operators", "-=", "#Subtraction_assignment")}}
+
Subtraction assignment
+
{{jsxref("Operators/Assignment_Operators", "<<=", "#Left_shift_assignment")}}
+
Left shift assignment.
+
{{jsxref("Operators/Assignment_Operators", ">>=", "#Right_shift_assignment")}}
+
Right shift assignment.
+
{{jsxref("Operators/Assignment_Operators", ">>>=", "#Unsigned_right_shift_assignment")}}
+
Unsigned right shift assignment.
+
{{jsxref("Operators/Assignment_Operators", "&=", "#Bitwise_AND_assignment")}}
+
Bitwise AND assignment.
+
{{jsxref("Operators/Assignment_Operators", "^=", "#Bitwise_XOR_assignment")}}
+
Bitwise XOR assignment.
+
{{jsxref("Operators/Assignment_Operators", "|=", "#Bitwise_OR_assignment")}}
+
Bitwise OR assignment.
+
{{jsxref("Operators/Destructuring_assignment", "[a, b] = [1, 2]")}}
+ {{jsxref("Operators/Destructuring_assignment", "{a, b} = {a:1, b:2}")}}
+
+

Destructuring assignment allows you to assign the properties of an array or object to variables using syntax that looks similar to array or object literals.

+
+
+ +

Operador de aspas

+ +
+
{{jsxref("Operators/Comma_Operator", ",")}}
+
The comma operator allows multiple expressions to be evaluated in a single statement and returns the result of the last expression.
+
+ +

Funcionalidades não padrão

+ +
+
{{non-standard_inline}} {{jsxref("Operators/Legacy_generator_function", "Legacy generator function", "", 1)}}
+
The function keyword can be used to define a legacy generator function inside an expression. To make the function a legacy generator, the function body should contains at least one {{jsxref("Operators/yield", "yield")}} expression.
+
{{non-standard_inline}} {{jsxref("Operators/Expression_closures", "Expression closures", "", 1)}}
+
The expression closure syntax is a shorthand for writing simple function.
+
{{non-standard_inline}} {{jsxref("Operators/Array_comprehensions", "[for (x of y) x]")}}
+
Array comprehensions.
+
{{non-standard_inline}} {{jsxref("Operators/Generator_comprehensions", "(for (x of y) y)")}}
+
Generator comprehensions.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('ES1', '#sec-11', 'Expressions')}}{{Spec2('ES1')}}Initial definition
{{SpecName('ES5.1', '#sec-11', 'Expressions')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}{{Spec2('ES6')}}New: Spread operator, destructuring assignment, super keyword.
{{SpecName('ESDraft', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}{{Spec2('ESDraft')}}
+ +

Compatibilidade de navegador

+ + + +

{{Compat("javascript.operators")}}

+ +

Consulte também

+ + diff --git a/files/pt-pt/web/javascript/reference/operators/operator_precedence/index.html b/files/pt-pt/web/javascript/reference/operators/operator_precedence/index.html new file mode 100644 index 0000000000..03d4345410 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/operators/operator_precedence/index.html @@ -0,0 +1,461 @@ +--- +title: Precedência de operador +slug: Web/JavaScript/Reference/Operadores/Precedencia_operador +tags: + - Guía + - JavaScript + - precedência +translation_of: Web/JavaScript/Reference/Operators/Operator_Precedence +--- +
{{jsSidebar("Operators")}}
+ +

A precedência de operador determina a maneira pela qual os operadores são analisados ​​em relação a cada um. Os operadores com maior precedência tornam-se operandos dos operadores com menor precedência..

+ +
{{EmbedInteractiveExample("pages/js/expressions-operatorprecedence.html")}}
+ + + +

Precedência e Associabilidade

+ +

Consider an expression describable by the representation below. Note that both OP1 and OPare fill-in-the-blanks for OPerators.

+ +
a OP b OP c
+
+ +

If OP1 and OP2 have different precedence levels (see the table below), the operator with the highest precedence goes first and associativity does not matter. Observe how multiplication has higher associativity than addition and executed first, even though addition is written first in the code.

+ +
console.log(3 + 10 * 2);   // logs 23
+console.log(3 + (10 * 2)); // logs 23 because parentheses here are superfluous
+console.log((3 + 10) * 2); // logs 26 because the parentheses change the order 
+ +

Left-associativity (left-to-right) means that it is processed as (a OP1 b) OP2 c, while right-associativity (right-to-left) means it is interpreted as a OP1 (b OP2 c). Assignment operators are right-associative, so you can write:

+ +
a = b = 5; // same as writing a = (b = 5);
+
+ +

with the expected result that a and b get the value 5. This is because the assignment operator returns the value that is assigned. First, b is set to 5. Then the a is also set to 5, the return value of b = 5, aka right operand of the assignment.

+ +

As another example, the unique exponentiation operator has right-associativity, whereas other arithmetic operators have left-associativity. It is interesting to note that, the order of evaluation is always left-to-right irregardless of associativity.

+ + + + + + + + + + + + + + + + +
CódigoResultado
+
+function echo(name, num) {
+    console.log("Evaluating the " + name + " side");
+    return num;
+}
+// Notice the division operator (/)
+console.log(echo("left", 6) / echo("right", 2));
+
+
+
+Evaluating the left side
+Evaluating the right side
+3
+
+
+
+function echo(name, num) {
+    console.log("Evaluating the " + name + " side");
+    return num;
+}
+// Notice the exponentiation operator (**)
+console.log(echo("left", 2) ** echo("right", 3));
+
+
+Evaluating the left side
+Evaluating the right side
+8
+
+ +

The difference in associativity comes into play when there are multiple operators of the same precedence. With only one operator or operators of different precedences, associativity does affect the output, as seen in the example above. In the example below, observe how associativity affects the output when multiple of the same operator are used.

+ + + + + + + + + + + + + + + + + + + + +
CódigoResultado
+
+function echo(name, num) {
+    console.log("Evaluating the " + name + " side");
+    return num;
+}
+// Notice the division operator (/)
+console.log(echo("left", 6) / echo("middle", 2) / echo("right", 3));
+
+
+
+Evaluating the left side
+Evaluating the middle side
+Evaluating the right side
+1
+
+
+
+function echo(name, num) {
+    console.log("Evaluating the " + name + " side");
+    return num;
+}
+// Notice the exponentiation operator (**)
+console.log(echo("left", 2) ** echo("middle", 3) ** echo("right", 2));
+
+
+
+Evaluating the left side
+Evaluating the middle side
+Evaluating the right side
+512
+
+
+
+function echo(name, num) {
+    console.log("Evaluating the " + name + " side");
+    return num;
+}
+// Notice the parentheses around the left and middle exponentiation
+console.log((echo("left", 2) ** echo("middle", 3)) ** echo("right", 2));
+
+
+Evaluating the left side
+Evaluating the middle side
+Evaluating the right side
+64
+
+ +

Looking at the code snippets above, 6 / 3 / 2 is the same as (6 / 3) / 2 because division is left-associative. Exponentiation, on the other hand, is right-associative, so 2 ** 3 ** 2 is the same as 2 ** (3 ** 2). Thus, doing (2 ** 3) ** 2 changes the order and results in the 64 seen in the table above.

+ +

Remember that precedence comes before associativity. So, mixing division and exponentiation, the exponentiation comes before the division. For example, 2 ** 3 / 3 ** 2 results in 0.8888888888888888 because it is the same as (2 ** 3) / (3 ** 2).

+ +

Note on Grouping and Short-Circuiting

+ +

In the table below, Grouping is listed as having the highest precedence. However, that does not always mean the expression within the grouping symbols ( … ) is evaluated first, especially when it comes to short-circuiting.

+ +

Short-circuiting is jargon for conditional evaluation. For example, in the expression a && (b + c), if a is “falsy”, then the sub-expression (b + c) will not even get evaluated, even if it is in parentheses. We could say that the logical disjunction operator (“OR”) is “short-circuited”. Along with logical disjunction, other short-circuited operators include logical conjunction (“AND”), nullish-coalescing, optional chaining, and the conditional operator. Some more examples follow.

+ +
a || (b * c);  // evaluate `a` first, then produce `a` if `a` is “truthy”
+a && (b < c);  // evaluate `a` first, then produce `a` if `a` is “falsy”
+a ?? (b || c); // evaluate `a` first, then produce `a` if `a` is not `null` and not `undefined`
+a?.b.c;        // evaluate `a` first, then produce `a` if `a` is `null` or `undefined`
+
+ +

Exemplos

+ +
3 > 2 && 2 > 1
+// returns true
+
+3 > 2 > 1
+// Returns false because 3 > 2 is true, then true is converted to 1 in inequality operators, therefore true > 1 becomes 1 > 1, which
+//  is false. Adding parentheses makes things clear: (3 > 2) > 1.
+
+
+ +

Tabela

+ +

The following table is ordered from highest (20) to lowest (1) precedence.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PrecedênciaTipo de operador (Operator)AssociatividadeOperadores individuais
20{{jsxref("Operators/Grouping", "Grouping")}}n/a( … )
19{{jsxref("Operators/Property_Accessors", "Member Access", "#Dot_notation")}}left-to-right… . …
{{jsxref("Operators/Property_Accessors", "Computed Member Access","#Bracket_notation")}}left-to-right… [ … ]
{{jsxref("Operators/new","new")}} (with argument list)n/anew … ( … )
Function Callleft-to-right… ( … )
18{{jsxref("Operators/new","new")}} (without argument list)right-to-leftnew …
17{{jsxref("Operators/Arithmetic_Operators","Postfix Increment","#Increment")}}n/a… ++
{{jsxref("Operators/Arithmetic_Operators","Postfix Decrement","#Decrement")}}… --
16Logical NOTright-to-left! …
Bitwise NOT~ …
Unary Plus+ …
Unary Negation- …
Prefix Increment++ …
Prefix Decrement-- …
typeoftypeof …
voidvoid …
deletedelete …
awaitawait …
15Exponentiationright-to-left… ** …
14Multiplicationleft-to-right… * …
Division… / …
Remainder… % …
13Additionleft-to-right… + …
Subtraction… - …
12Bitwise Left Shiftleft-to-right… << …
Bitwise Right Shift… >> …
Bitwise Unsigned Right Shift… >>> …
11Less Thanleft-to-right… < …
Less Than Or Equal… <= …
Greater Than… > …
Greater Than Or Equal… >= …
in… in …
instanceof… instanceof …
10Equalityleft-to-right… == …
Inequality… != …
Strict Equality… === …
Strict Inequality… !== …
9Bitwise ANDleft-to-right… & …
8Bitwise XORleft-to-right… ^ …
7Bitwise ORleft-to-right… | …
6Logical ANDleft-to-right… && …
5Logical ORleft-to-right… || …
4Conditionalright-to-left… ? … : …
3Assignmentright-to-left… = …
… += …
… -= …
… **= …
… *= …
… /= …
… %= …
… <<= …
… >>= …
… >>>= …
… &= …
… ^= …
… |= …
2{{jsxref("Operators/yield", "yield")}}right-to-leftyield …
{{jsxref("Operators/yield*", "yield*")}}yield* …
1Vírgula / Sequêncialeft-to-right… , …
diff --git a/files/pt-pt/web/javascript/reference/sobre/index.html b/files/pt-pt/web/javascript/reference/sobre/index.html deleted file mode 100644 index 3b2a79ac32..0000000000 --- a/files/pt-pt/web/javascript/reference/sobre/index.html +++ /dev/null @@ -1,52 +0,0 @@ ---- -title: Sobre a referência de JavaScript -slug: Web/JavaScript/Reference/Sobre -tags: - - JavaScript -translation_of: Web/JavaScript/Reference/About ---- -
{{JsSidebar}}
- -

The JavaScript reference serves as a repository of facts about the JavaScript language. The entire language is described here in detail. As you write JavaScript code, you'll refer to these pages often (thus the title "JavaScript reference"). If you're learning JavaScript, or need help understanding some of its capabilities or features, check out the JavaScript guide.

- -

The JavaScript language is intended to be used within some larger environment, be it a browser, server-side scripts, or similar. For the most part, this reference attempts to be environment-agnostic and does not target a web browser environment.

- -

Onde encontrar informação sobre JavaScript

- -

JavaScript documentation of core language features (pure ECMAScript, for the most part) includes the following:

- - - -

If you are new to JavaScript, start with the guide. Once you have a firm grasp of the fundamentals, you can use the reference to get more details on individual objects and language constructs.

- -

Estrutura da referência

- -

In the JavaScript reference you can find the following chapters:

- -
-
Standard built-in objects
-
This chapter documents all the JavaScript standard built-in objects, along with their methods and properties.
-
Statements and declarations
-
JavaScript applications consist of statements with an appropriate syntax. A single statement may span multiple lines. Multiple statements may occur on a single line if each statement is separated by a semicolon. This isn't a keyword, but a group of keywords.
-
Expressions and operators
-
This chapter documents all the JavaScript language operators, expressions and keywords.
-
Functions
-
Chapter about JavaScript functions.
-
Classes
-
Chapter about JavaScript classes introduced in ECMAScript 6.
-
Errors
-
Chapter about specific errors, exceptions and warnings thrown by JavaScript.
-
New in JavaScript
-
Chapter about JavaScript version history.
-
- -

Mais páginas de referência

- - diff --git a/files/pt-pt/web/javascript/reference/statements/block/index.html b/files/pt-pt/web/javascript/reference/statements/block/index.html new file mode 100644 index 0000000000..a3104dbeae --- /dev/null +++ b/files/pt-pt/web/javascript/reference/statements/block/index.html @@ -0,0 +1,116 @@ +--- +title: Bloco (block) +slug: Web/JavaScript/Reference/Extratos_e_declarações/bloco +tags: + - Declaração + - Funcionalidade de Linguagem + - JavaScript + - Referencia +translation_of: Web/JavaScript/Reference/Statements/block +--- +
Bloco {{jsSidebar("Statements")}}
+ +

Uma declaralção bloco (ou declaração composto em outras linguagens) é utilizada para agrupar zero ou mais declarações. O bloco é delimitado por um par de chavetas (“chavetas { }”) e opcionalmente poderá ser {{jsxref("Statements/label", "labelled", "", 1)}}:

+ +
{{EmbedInteractiveExample("pages/js/statement-block.html", "taller")}}
+ + + +

Sintaxe

+ +

Declaração de Bloco

+ +
{
+  StatementList
+}
+
+ +

Declaração de Bloco Etiquetado

+ +
LabelIdentifier: {
+  StatementList
+}
+
+ +
+
StatementList
+
Statements grouped within the block statement.
+
LabelIdentifier
+
An optional {{jsxref("Statements/label", "label", "", 1)}} for visual identification or as a target for {{jsxref("Statements/break", "break")}}.
+
+ +

Descrição

+ +

The block statement is often called compound statement in other languages. It allows you to use multiple statements where JavaScript expects only one statement. Combining statements into blocks is a common practice in JavaScript. The opposite behavior is possible using an empty statement, where you provide no statement, although one is required.

+ +

Blocks are commonly used in association with {{jsxref("Statements/if...else", "if...else")}} and {{jsxref("Statements/for", "for")}} statements.

+ +

Block Scoping Rules

+ +

With var or function declaration in non-strict mode

+ +

Variables declared with var or created by function declarations in non-strict mode do not have block scope. Variables introduced within a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. In other words, block statements do not introduce a scope. For example:

+ +
var x = 1;
+{
+  var x = 2;
+}
+console.log(x); // logs 2
+
+ +

This logs 2 because the var x statement within the block is in the same scope as the var x statement before the block.

+ +

In non-strict code, function declarations inside blocks behave strangely. Do not use them.

+ +

With let, const or function declaration in strict mode

+ +

By contrast, identifiers declared with {{jsxref("Statements/let", "let")}} and {{jsxref("Statements/const", "const")}} do have block scope:

+ +
let x = 1;
+{
+  let x = 2;
+}
+console.log(x); // logs 1
+ +

The x = 2 is limited in scope to the block in which it was defined.

+ +

The same is true of const:

+ +
const c = 1;
+{
+  const c = 2;
+}
+console.log(c); // logs 1 and does not throw SyntaxError...
+ +

Note that the block-scoped const c = 2 does not throw a SyntaxError: Identifier 'c' has already been declared because it can be declared uniquely within the block.

+ +

In strict mode, starting with ES2015, functions inside blocks are scoped to that block. Prior to ES2015, block-level functions were forbidden in strict mode.

+ +

Especificações

+ + + + + + + + + + + + +
Especificação
{{SpecName('ESDraft', '#sec-block', 'Block statement')}}
+ +

Compatibilidade de navegador

+ + + +

{{Compat("javascript.statements.block")}}

+ +

Consulte também

+ + diff --git a/files/pt-pt/web/javascript/reference/statements/for/index.html b/files/pt-pt/web/javascript/reference/statements/for/index.html new file mode 100644 index 0000000000..ac7586e98b --- /dev/null +++ b/files/pt-pt/web/javascript/reference/statements/for/index.html @@ -0,0 +1,145 @@ +--- +title: for +slug: Web/JavaScript/Reference/Extratos_e_declarações/for +tags: + - Declaração + - Funcionalidade de Linguagem + - JavaScript + - Loop + - Referencia + - Repetição + - for +translation_of: Web/JavaScript/Reference/Statements/for +--- +
{{jsSidebar("Statements")}}
+ +

A declaração "for" cria uma repetição (loop) que consiste de três expressões opcionais, entre parênteses e separados por ponto e vírgula, seguido de uma declaração (normalmente bdeclaraçãod e bloco (block)) para ser executada na repetição.

+ +
{{EmbedInteractiveExample("pages/js/statement-for.html")}}
+ + + +

Sintaxe

+ +
for ([initialization]; [condition]; [final-expression])
+   statement
+ +
+
initialization
+
An expression (including assignment expressions) or variable declaration evaluated once before the loop begins. Typically used to initialize a counter variable. This expression may optionally declare new variables with var or let keywords. Variables declared with var are not local to the loop, i.e. they are in the same scope the for loop is in. Variables declared with let are local to the statement.
+
The result of this expression is discarded.
+
condition
+
An expression to be evaluated before each loop iteration. If this expression evaluates to true, statement is executed. This conditional test is optional. If omitted, the condition always evaluates to true. If the expression evaluates to false, execution skips to the first expression following the for construct.
+
final-expression
+
An expression to be evaluated at the end of each loop iteration. This occurs before the next evaluation of condition. Generally used to update or increment the counter variable.
+
statement
+
A statement that is executed as long as the condition evaluates to true. To execute multiple statements within the loop, use a {{jsxref("Statements/block", "block", "", 0)}} statement ({ ... }) to group those statements. To execute no statement within the loop, use an {{jsxref("Statements/empty", "empty", "", 0)}} statement (;).
+
+ +

Exemplos

+ +

Using for

+ +

The following for statement starts by declaring the variable i and initializing it to 0. It checks that i is less than nine, performs the two succeeding statements, and increments i by 1 after each pass through the loop.

+ +
for (let i = 0; i < 9; i++) {
+   console.log(i);
+   // more statements
+}
+
+ +

Optional for expressions

+ +

All three expressions in the head of the for loop are optional.

+ +

For example, in the initialization block it is not required to initialize variables:

+ +
var i = 0;
+for (; i < 9; i++) {
+    console.log(i);
+    // more statements
+}
+
+ +

Like the initialization block, the condition block is also optional. If you are omitting this expression, you must make sure to break the loop in the body in order to not create an infinite loop.

+ +
for (let i = 0;; i++) {
+   console.log(i);
+   if (i > 3) break;
+   // more statements
+}
+ +

You can also omit all three blocks. Again, make sure to use a {{jsxref("Statements/break", "break")}} statement to end the loop and also modify (increase) a variable, so that the condition for the break statement is true at some point.

+ +
var i = 0;
+
+for (;;) {
+  if (i > 3) break;
+  console.log(i);
+  i++;
+}
+
+ +

Using for without a statement

+ +

The following for cycle calculates the offset position of a node in the final-expression section, and therefore it does not require the use of a statement section, a semicolon is used instead.

+ +
function showOffsetPos(sId) {
+
+  var nLeft = 0, nTop = 0;
+
+  for (
+
+    var oItNode = document.getElementById(sId); /* initialization */
+
+    oItNode; /* condition */
+
+    nLeft += oItNode.offsetLeft, nTop += oItNode.offsetTop, oItNode = oItNode.offsetParent /* final-expression */
+
+  ); /* semicolon */
+
+  console.log('Offset position of \'' + sId + '\' element:\n left: ' + nLeft + 'px;\n top: ' + nTop + 'px;');
+
+}
+
+/* Example call: */
+
+showOffsetPos('content');
+
+// Output:
+// "Offset position of "content" element:
+// left: 0px;
+// top: 153px;"
+ +
Note: This is one of the few cases in JavaScript where the semicolon is mandatory. Indeed, without the semicolon the line that follows the cycle declaration will be considered a statement.
+ +

Especificações

+ + + + + + + + + + +
Especificação
{{SpecName('ESDraft', '#sec-for-statement', 'for statement')}}
+ +

Compatibilidade de navegador

+ + + +

{{Compat("javascript.statements.for")}}

+ +

Consulte também

+ + diff --git a/files/pt-pt/web/javascript/reference/statements/index.html b/files/pt-pt/web/javascript/reference/statements/index.html new file mode 100644 index 0000000000..af841906a1 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/statements/index.html @@ -0,0 +1,150 @@ +--- +title: Declarações e instruções +slug: Web/JavaScript/Reference/Extratos_e_declarações +tags: + - JavaScript + - Referencia + - declarações + - instruções +translation_of: Web/JavaScript/Reference/Statements +--- +
{{jsSidebar("Statements")}}
+ +

JavaScript applications consist of statements with an appropriate syntax. A single statement may span multiple lines. Multiple statements may occur on a single line if each statement is separated by a semicolon. This isn't a keyword, but a group of keywords.

+ +

Declarações e instruções por categoria

+ +

For an alphabetical listing see the sidebar on the left.

+ +

Controlo de Fluxo

+ +
+
{{jsxref("Statements/block", "Block")}}
+
A block statement is used to group zero or more statements. The block is delimited by a pair of curly brackets.
+
{{jsxref("Statements/break", "break")}}
+
Terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement.
+
{{jsxref("Statements/continue", "continue")}}
+
Terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.
+
{{jsxref("Statements/Empty", "Empty")}}
+
An empty statement is used to provide no statement, although the JavaScript syntax would expect one.
+
{{jsxref("Statements/if...else", "if...else")}}
+
Executes a statement if a specified condition is true. If the condition is false, another statement can be executed.
+
{{jsxref("Statements/switch", "switch")}}
+
Evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case.
+
{{jsxref("Statements/throw", "throw")}}
+
Throws a user-defined exception.
+
{{jsxref("Statements/try...catch", "try...catch")}}
+
Marks a block of statements to try, and specifies a response, should an exception be thrown.
+
+ +

Declarações

+ +
+
{{jsxref("Statements/var", "var")}}
+
Declares a variable, optionally initializing it to a value.
+
{{jsxref("Statements/let", "let")}}
+
Declares a block scope local variable, optionally initializing it to a value.
+
{{jsxref("Statements/const", "const")}}
+
Declares a read-only named constant.
+
+ +

Funções e classes

+ +
+
{{jsxref("Statements/function", "function")}}
+
Declara as funções com parâmetros especificados.
+
{{jsxref("Statements/function*", "function*")}}
+
Generators functions enable writing iterators more easily.
+
{{jsxref("Statements/async_function", "async function")}}
+
Declares an async function with the specified parameters.
+
{{jsxref("Statements/return", "return")}}
+
Specifies the value to be returned by a function.
+
{{jsxref("Statements/class", "class")}}
+
Declara uma Classe.
+
+ +

Iterações

+ +
+
{{jsxref("Statements/do...while", "do...while")}}
+
Creates a loop that executes a specified statement until the test condition evaluates to false. The condition is evaluated after executing the statement, resulting in the specified statement executing at least once.
+
{{jsxref("Statements/for", "for")}}
+
Creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.
+
{{deprecated_inline}} {{non-standard_inline()}} {{jsxref("Statements/for_each...in", "for each...in")}}
+
Iterates a specified variable over all values of object's properties. For each distinct property, a specified statement is executed.
+
{{jsxref("Statements/for...in", "for...in")}}
+
Iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.
+
{{jsxref("Statements/for...of", "for...of")}}
+
Iterates over iterable objects (including {{jsxref("Global_Objects/Array","arrays","","true")}}, array-like objects, iterators and generators), invoking a custom iteration hook with statements to be executed for the value of each distinct property.
+
{{jsxref("Statements/while", "while")}}
+
Creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement.
+
+ +

Outros

+ +
+
{{jsxref("Statements/debugger", "debugger")}}
+
Invokes any available debugging functionality. If no debugging functionality is available, this statement has no effect.
+
{{jsxref("Statements/export", "export")}}
+
Used to export functions to make them available for imports in external modules, another scripts.
+
{{jsxref("Statements/import", "import")}}
+
Used to import functions exported from an external module, another script.
+
import.meta
+
A meta-property exposing context-specific metadata to a JavaScript module.
+
{{jsxref("Statements/label", "label")}}
+
Provides a statement with an identifier that you can refer to using a break or continue statement.
+
+ +
+
{{deprecated_inline}} {{jsxref("Statements/with", "with")}}
+
Extends the scope chain for a statement.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('ES1', '#sec-12', 'Statements')}}{{Spec2('ES1')}}Initial definition
{{SpecName('ES3', '#sec-12', 'Statements')}}{{Spec2('ES3')}} 
{{SpecName('ES5.1', '#sec-12', 'Statements')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}{{Spec2('ES6')}}New: function*, let, for...of, yield, class
{{SpecName('ESDraft', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidade de navegador

+ + + +

{{Compat("javascript.statements")}}

+ +

Consultar também

+ + diff --git a/files/pt-pt/web/javascript/reference/statements/return/index.html b/files/pt-pt/web/javascript/reference/statements/return/index.html new file mode 100644 index 0000000000..6cec134992 --- /dev/null +++ b/files/pt-pt/web/javascript/reference/statements/return/index.html @@ -0,0 +1,148 @@ +--- +title: return +slug: Web/JavaScript/Reference/Extratos_e_declarações/return +tags: + - Declaração + - JavaScript +translation_of: Web/JavaScript/Reference/Statements/return +--- +
{{jsSidebar("Statements")}}
+ +

The return statement ends function execution and specifies a value to be returned to the function caller.

+ +

Sintaxe

+ +
return [[expression]]; 
+ +
+
expression
+
The expression whose value is to be returned. If omitted, undefined is returned instead.
+
+ +

Descrição

+ +

When a return statement is used in a function body, the execution of the function is stopped. If specified, a given value is returned to the function caller. For example, the following function returns the square of its argument, x, where x is a number.

+ +
function square(x) {
+   return x * x;
+}
+var demo = square(3);
+// demo will equal 9
+
+ +

If the value is omitted, undefined is returned instead.

+ +

The following return statements all break the function execution:

+ +
return;
+return true;
+return false;
+return x;
+return x + y / 3;
+
+ +

Inserção Automática de Ponto e Vírgula

+ +

The return statement is affected by automatic semicolon insertion (ASI). No line terminator is allowed between the return keyword and the expression.

+ +
return
+a + b;
+
+ +

is transformed by ASI into:

+ +
return;
+a + b;
+
+ +

The console will warn "unreachable code after return statement".

+ +
Starting with Gecko 40 {{geckoRelease(40)}}, a warning is shown in the console if unreachable code is found after a return statement.
+ +

Exemplos

+ +

Interromper uma função

+ +

A function immediately stops at the point where return is called.

+ +
function counter() {
+  for (var count = 1; ; count++) {  // infinite loop
+    console.log(count + 'A'); // until 5
+      if (count === 5) {
+        return;
+      }
+      console.log(count + 'B');  // until 4
+    }
+  console.log(count + 'C');  // never appears
+}
+
+counter();
+
+// Output:
+// 1A
+// 1B
+// 2A
+// 2B
+// 3A
+// 3B
+// 4A
+// 4B
+// 5A
+
+ +

Devolver uma função

+ +

See also the article about Closures.

+ +
function magic(x) {
+  return function calc(x) { return x * 42; };
+}
+
+var answer = magic();
+answer(1337); // 56154
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-12.9', 'Return statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-return-statement', 'Return statement')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-return-statement', 'Return statement')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidade de navegador

+ + + +

{{Compat("javascript.statements.return")}}

+ +

Consulte também

+ + diff --git a/files/pt-pt/web/javascript/reference/statements/throw/index.html b/files/pt-pt/web/javascript/reference/statements/throw/index.html new file mode 100644 index 0000000000..9e7a8bf54e --- /dev/null +++ b/files/pt-pt/web/javascript/reference/statements/throw/index.html @@ -0,0 +1,271 @@ +--- +title: throw +slug: Web/JavaScript/Reference/Extratos_e_declarações/throw +tags: + - Comando + - Declaração + - JavaScript +translation_of: Web/JavaScript/Reference/Statements/throw +--- +
{{jsSidebar("Statements")}}
+ +

A declaração throw lança uma exeção definida pelo utilizador. A execução da função atual irá parar (os comandos depois de throw não serão executados), e o controle será passado para o primeiro bloco catch no conjunto de chamadas. Se não existir nenhum bloco catch entre as funções de caller, o programa irá terminar.

+ +

Sintaxe

+ +
expressão throw; 
+ +
+
expressão
+
A expressão para throw.
+
+ +

Descrição

+ +

Use the throw statement to throw an exception. When you throw an exception, expression specifies the value of the exception. Each of the following throws an exception:

+ +
throw 'Error2'; // generates an exception with a string value
+throw 42;       // generates an exception with the value 42
+throw true;     // generates an exception with the value true
+ +

Also note that the throw statement is affected by automatic semicolon insertion (ASI) as no line terminator between the throw keyword and the expression is allowed.

+ +

Exemplos

+ +

Throw um objeto

+ +

You can specify an object when you throw an exception. You can then reference the object's properties in the catch block. The following example creates an object of type UserException and uses it in a throw statement.

+ +
function UserException(message) {
+   this.message = message;
+   this.name = 'UserException';
+}
+function getMonthName(mo) {
+   mo = mo - 1; // Adjust month number for array index (1 = Jan, 12 = Dec)
+   var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
+      'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
+   if (months[mo] !== undefined) {
+      return months[mo];
+   } else {
+      throw new UserException('InvalidMonthNo');
+   }
+}
+
+try {
+   // statements to try
+   var myMonth = 15; // 15 is out of bound to raise the exception
+   var monthName = getMonthName(myMonth);
+} catch (e) {
+   monthName = 'unknown';
+   console.log(e.message, e.name); // pass exception object to err handler
+}
+
+ +

Outro exemplo de throwing um objeto

+ +

The following example tests an input string for a U.S. zip code. If the zip code uses an invalid format, the throw statement throws an exception by creating an object of type ZipCodeFormatException.

+ +
/*
+ * Creates a ZipCode object.
+ *
+ * Accepted formats for a zip code are:
+ *    12345
+ *    12345-6789
+ *    123456789
+ *    12345 6789
+ *
+ * If the argument passed to the ZipCode constructor does not
+ * conform to one of these patterns, an exception is thrown.
+ */
+
+function ZipCode(zip) {
+   zip = new String(zip);
+   pattern = /[0-9]{5}([- ]?[0-9]{4})?/;
+   if (pattern.test(zip)) {
+      // zip code value will be the first match in the string
+      this.value = zip.match(pattern)[0];
+      this.valueOf = function() {
+         return this.value
+      };
+      this.toString = function() {
+         return String(this.value)
+      };
+   } else {
+      throw new ZipCodeFormatException(zip);
+   }
+}
+
+function ZipCodeFormatException(value) {
+   this.value = value;
+   this.message = 'does not conform to the expected format for a zip code';
+   this.toString = function() {
+      return this.value + this.message;
+   };
+}
+
+/*
+ * This could be in a script that validates address data
+ * for US addresses.
+ */
+
+const ZIPCODE_INVALID = -1;
+const ZIPCODE_UNKNOWN_ERROR = -2;
+
+function verifyZipCode(z) {
+   try {
+      z = new ZipCode(z);
+   } catch (e) {
+      if (e instanceof ZipCodeFormatException) {
+         return ZIPCODE_INVALID;
+      } else {
+         return ZIPCODE_UNKNOWN_ERROR;
+      }
+   }
+   return z;
+}
+
+a = verifyZipCode(95060);         // returns 95060
+b = verifyZipCode(9560);          // returns -1
+c = verifyZipCode('a');           // returns -1
+d = verifyZipCode('95060');       // returns 95060
+e = verifyZipCode('95060 1234');  // returns 95060 1234
+
+ +

Rethrow uma exceção

+ +

You can use throw to rethrow an exception after you catch it. The following example catches an exception with a numeric value and rethrows it if the value is over 50. The rethrown exception propagates up to the enclosing function or to the top level so that the user sees it.

+ +
try {
+   throw n; // throws an exception with a numeric value
+} catch (e) {
+   if (e <= 50) {
+      // statements to handle exceptions 1-50
+   } else {
+      // cannot handle this exception, so rethrow
+      throw e;
+   }
+}
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.4
{{SpecName('ES5.1', '#sec-12.13', 'throw statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-throw-statement', 'throw statement')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-throw-statement', 'throw statement')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidade de navegador

+ + + +

{{Compat("javascript.statements.throw")}}

+ +

Consulte também

+ + + +
+ + + + + +
diff --git a/files/pt-pt/web/javascript/shells/index.html b/files/pt-pt/web/javascript/shells/index.html new file mode 100644 index 0000000000..b773a327dc --- /dev/null +++ b/files/pt-pt/web/javascript/shells/index.html @@ -0,0 +1,29 @@ +--- +title: JavaScript Shells +slug: JavaScript_Shells +tags: + - 'Extensões:Ferramentas' + - Ferramentas + - JavaScript + - 'JavaScript:Ferramentas' +--- +

Um shell JavaScript permite a você rapidamente testar partes de código JavaScript sem ter que atualizar a página web. Eles são extremamente úteis para desenvolvimento e depuração de código.

+ +

Lista de shells JavaScript

+ +

Os seguintes shells JavaScript trabalham com o Mozilla:

+ + + +

Categorias

+ +

Add Interwiki Languages

-- cgit v1.2.3-54-g00ecf