From f3fb7d2927a16e702ac7683957ff2981c86d31c5 Mon Sep 17 00:00:00 2001 From: odsantos Date: Tue, 22 Oct 2019 05:42:38 +0100 Subject: [PATCH 1/3] translate '01-object' directory files --- .../01-object/2-hello-object/solution.md | 2 - .../01-object/2-hello-object/task.md | 14 +- .../01-object/3-is-empty/_js.view/solution.js | 2 +- .../01-object/3-is-empty/_js.view/test.js | 4 +- .../01-object/3-is-empty/solution.md | 2 +- .../01-object/3-is-empty/task.md | 13 +- .../01-object/4-const-object/solution.md | 10 +- .../01-object/4-const-object/task.md | 6 +- .../01-object/5-sum-object/task.md | 8 +- .../8-multiply-numeric/_js.view/source.js | 6 +- .../8-multiply-numeric/_js.view/test.js | 8 +- .../01-object/8-multiply-numeric/task.md | 20 +- 1-js/04-object-basics/01-object/article.md | 473 +++++++++--------- 1-js/04-object-basics/index.md | 2 +- 14 files changed, 281 insertions(+), 289 deletions(-) diff --git a/1-js/04-object-basics/01-object/2-hello-object/solution.md b/1-js/04-object-basics/01-object/2-hello-object/solution.md index 60083b963..dff006076 100644 --- a/1-js/04-object-basics/01-object/2-hello-object/solution.md +++ b/1-js/04-object-basics/01-object/2-hello-object/solution.md @@ -1,5 +1,4 @@ - ```js let user = {}; user.name = "John"; @@ -7,4 +6,3 @@ user.surname = "Smith"; user.name = "Pete"; delete user.name; ``` - diff --git a/1-js/04-object-basics/01-object/2-hello-object/task.md b/1-js/04-object-basics/01-object/2-hello-object/task.md index 2841a058f..c0e296444 100644 --- a/1-js/04-object-basics/01-object/2-hello-object/task.md +++ b/1-js/04-object-basics/01-object/2-hello-object/task.md @@ -2,13 +2,13 @@ importance: 5 --- -# Hello, object +# Olá, objeto -Write the code, one line for each action: +Escreva o código, uma ação por linha: -1. Create an empty object `user`. -2. Add the property `name` with the value `John`. -3. Add the property `surname` with the value `Smith`. -4. Change the value of the `name` to `Pete`. -5. Remove the property `name` from the object. +1. Crie um objeto vazio (*empty object*) `user`. +2. Adicione a propriedade `name` com o valor `John`. +3. Adicione a propriedade `surname` com o valor `Smith`. +4. Altere o valor de `name` para `Pete`. +5. Remova a propriedade `name` do objeto. diff --git a/1-js/04-object-basics/01-object/3-is-empty/_js.view/solution.js b/1-js/04-object-basics/01-object/3-is-empty/_js.view/solution.js index db3283e49..ca7dc324e 100644 --- a/1-js/04-object-basics/01-object/3-is-empty/_js.view/solution.js +++ b/1-js/04-object-basics/01-object/3-is-empty/_js.view/solution.js @@ -1,6 +1,6 @@ function isEmpty(obj) { for (let key in obj) { - // if the loop has started, there is a property + // se o laço começou, existe uma propriedade return false; } return true; diff --git a/1-js/04-object-basics/01-object/3-is-empty/_js.view/test.js b/1-js/04-object-basics/01-object/3-is-empty/_js.view/test.js index 4db5efabe..400577698 100644 --- a/1-js/04-object-basics/01-object/3-is-empty/_js.view/test.js +++ b/1-js/04-object-basics/01-object/3-is-empty/_js.view/test.js @@ -1,9 +1,9 @@ describe("isEmpty", function() { - it("returns true for an empty object", function() { + it("retorna verdadeiro para um objeto vazio", function() { assert.isTrue(isEmpty({})); }); - it("returns false if a property exists", function() { + it("retorna falso se uma propriedade existir", function() { assert.isFalse(isEmpty({ anything: false })); diff --git a/1-js/04-object-basics/01-object/3-is-empty/solution.md b/1-js/04-object-basics/01-object/3-is-empty/solution.md index b876973b5..6c328fc39 100644 --- a/1-js/04-object-basics/01-object/3-is-empty/solution.md +++ b/1-js/04-object-basics/01-object/3-is-empty/solution.md @@ -1 +1 @@ -Just loop over the object and `return false` immediately if there's at least one property. +Simplemente, percorra (*loop over*) o objeto e imediatamente `return false` se pelo menos houver uma propriedade. diff --git a/1-js/04-object-basics/01-object/3-is-empty/task.md b/1-js/04-object-basics/01-object/3-is-empty/task.md index c438d36a2..a499e6eb7 100644 --- a/1-js/04-object-basics/01-object/3-is-empty/task.md +++ b/1-js/04-object-basics/01-object/3-is-empty/task.md @@ -2,19 +2,18 @@ importance: 5 --- -# Check for emptiness +# Verifique por vazio (*emptiness*) -Write the function `isEmpty(obj)` which returns `true` if the object has no properties, `false` otherwise. - -Should work like that: +Escreva a função `isEmpty(obj)`, que retorna `true` se o objeto não tiver propriedades, e `false` caso contrário. +Deve assim funcionar: ```js let schedule = {}; -alert( isEmpty(schedule) ); // true +alert( isEmpty(schedule) ); // verdadeiro -schedule["8:30"] = "get up"; +schedule["8:30"] = "levante-se"; -alert( isEmpty(schedule) ); // false +alert( isEmpty(schedule) ); // falso ``` diff --git a/1-js/04-object-basics/01-object/4-const-object/solution.md b/1-js/04-object-basics/01-object/4-const-object/solution.md index f73c2f92b..9cb150373 100644 --- a/1-js/04-object-basics/01-object/4-const-object/solution.md +++ b/1-js/04-object-basics/01-object/4-const-object/solution.md @@ -1,8 +1,8 @@ -Sure, it works, no problem. +Com certeza, funciona, sem problemas. -The `const` only protects the variable itself from changing. +A `const` apenas protege a própria variável contra alterações. -In other words, `user` stores a reference to the object. And it can't be changed. But the content of the object can. +Por outras palavras, `user` armazena uma referência ao objeto. E não pode ser alterada. Mas, o conteúdo do objeto pode. ```js run const user = { @@ -10,10 +10,10 @@ const user = { }; *!* -// works +// funciona user.name = "Pete"; */!* -// error +// erro user = 123; ``` diff --git a/1-js/04-object-basics/01-object/4-const-object/task.md b/1-js/04-object-basics/01-object/4-const-object/task.md index a9aada631..a0a1709dc 100644 --- a/1-js/04-object-basics/01-object/4-const-object/task.md +++ b/1-js/04-object-basics/01-object/4-const-object/task.md @@ -2,9 +2,9 @@ importance: 5 --- -# Constant objects? +# Objetos constantes? -Is it possible to change an object declared with `const`? What do you think? +É possível alterar um objeto declarado com `const`? O que acha? ```js const user = { @@ -12,7 +12,7 @@ const user = { }; *!* -// does it work? +// isto funciona? user.name = "Pete"; */!* ``` diff --git a/1-js/04-object-basics/01-object/5-sum-object/task.md b/1-js/04-object-basics/01-object/5-sum-object/task.md index 7e3e048d0..b0caee202 100644 --- a/1-js/04-object-basics/01-object/5-sum-object/task.md +++ b/1-js/04-object-basics/01-object/5-sum-object/task.md @@ -2,9 +2,9 @@ importance: 5 --- -# Sum object properties +# Soma das propriedades de um objeto -We have an object storing salaries of our team: +Temos um objeto armazenando salários da nossa equipa: ```js let salaries = { @@ -14,6 +14,6 @@ let salaries = { } ``` -Write the code to sum all salaries and store in the variable `sum`. Should be `390` in the example above. +Escreva o código para somar todos os salários e armazenar na variável `sum`. Para o exemplo acima, deverá ser `390`. -If `salaries` is empty, then the result must be `0`. \ No newline at end of file +Se `salaries` for vazio, então o resultado deve ser `0`. \ No newline at end of file diff --git a/1-js/04-object-basics/01-object/8-multiply-numeric/_js.view/source.js b/1-js/04-object-basics/01-object/8-multiply-numeric/_js.view/source.js index a02b1e1cb..f2ffe4901 100644 --- a/1-js/04-object-basics/01-object/8-multiply-numeric/_js.view/source.js +++ b/1-js/04-object-basics/01-object/8-multiply-numeric/_js.view/source.js @@ -1,17 +1,17 @@ let menu = { width: 200, height: 300, - title: "My menu" + title: "O meu menu" }; function multiplyNumeric(obj) { - /* your code */ + /* o seu código */ } multiplyNumeric(menu); -alert( "menu width=" + menu.width + " height=" + menu.height + " title=" + menu.title ); +alert( "largura do menu=" + menu.width + " altura=" + menu.height + " título=" + menu.title ); diff --git a/1-js/04-object-basics/01-object/8-multiply-numeric/_js.view/test.js b/1-js/04-object-basics/01-object/8-multiply-numeric/_js.view/test.js index 064e5414f..2ba28f769 100644 --- a/1-js/04-object-basics/01-object/8-multiply-numeric/_js.view/test.js +++ b/1-js/04-object-basics/01-object/8-multiply-numeric/_js.view/test.js @@ -1,17 +1,17 @@ describe("multiplyNumeric", function() { - it("multiplies all numeric properties by 2", function() { + it("multiplica todas as propriedades numéricas por 2", function() { let menu = { width: 200, height: 300, - title: "My menu" + title: "O meu menu" }; let result = multiplyNumeric(menu); assert.equal(menu.width, 400); assert.equal(menu.height, 600); - assert.equal(menu.title, "My menu"); + assert.equal(menu.title, "O meu menu"); }); - it("returns nothing", function() { + it("não retorna nada", function() { assert.isUndefined( multiplyNumeric({}) ); }); diff --git a/1-js/04-object-basics/01-object/8-multiply-numeric/task.md b/1-js/04-object-basics/01-object/8-multiply-numeric/task.md index 33eb89220..54fa7fceb 100644 --- a/1-js/04-object-basics/01-object/8-multiply-numeric/task.md +++ b/1-js/04-object-basics/01-object/8-multiply-numeric/task.md @@ -2,32 +2,30 @@ importance: 3 --- -# Multiply numeric properties by 2 +# Multiplica as propriedades numéricas por 2 -Create a function `multiplyNumeric(obj)` that multiplies all numeric properties of `obj` by `2`. +Crie uma função `multiplyNumeric(obj)` que multiplica todas as proriedades numéricas de `obj` por `2`. -For instance: +Por exemplo: ```js -// before the call +// antes da chamada let menu = { width: 200, height: 300, - title: "My menu" + title: "O meu menu" }; multiplyNumeric(menu); -// after the call +// depois da chamada menu = { width: 400, height: 600, - title: "My menu" + title: "O meu menu" }; ``` -Please note that `multiplyNumeric` does not need to return anything. It should modify the object in-place. - -P.S. Use `typeof` to check for a number here. - +Por favor, note que `multiplyNumeric` não precisa de retornar nada. Deve modificar o próprio objecto. +P.S. Use `typeof` para verificar por um número aqui. diff --git a/1-js/04-object-basics/01-object/article.md b/1-js/04-object-basics/01-object/article.md index 00706750c..baba98e3a 100644 --- a/1-js/04-object-basics/01-object/article.md +++ b/1-js/04-object-basics/01-object/article.md @@ -1,60 +1,60 @@ -# Objects +# Objetos -As we know from the chapter , there are seven data types in JavaScript. Six of them are called "primitive", because their values contain only a single thing (be it a string or a number or whatever). +Como sabemos, pelo capítulo , existem sete tipos de dados em JavaScript. Seis deles são chamados de "primitivos", porque os seus valores apenas contêm uma única coisa (seja ela uma cadeia-de-carateres [*string*], um número, ou o que for). -In contrast, objects are used to store keyed collections of various data and more complex entities. In JavaScript, objects penetrate almost every aspect of the language. So we must understand them first before going in-depth anywhere else. +Em contraste, objetos são empregues para armazenar por meio de uma chave, coleções de vários dados e entidades mais complexas. Em JavaScript, objetos penetram em quase todos os aspetos da linguagem. Portanto, devemos primeiro compreendê-los antes de nos envolvermos detalhadamente em algo mais. -An object can be created with figure brackets `{…}` with an optional list of *properties*. A property is a "key: value" pair, where `key` is a string (also called a "property name"), and `value` can be anything. +Um objeto pode ser criado por chavetas `{…}`, com uma lista opcional de *propriedades*. Uma propriedade é um par "key: value" (chave: valor), onde `key` é uma *string* (também chamada de "nome da propriedade"), e `value` pode ser qualquer coisa. -We can imagine an object as a cabinet with signed files. Every piece of data is stored in its file by the key. It's easy to find a file by its name or add/remove a file. +Podemos imaginar um objeto como um fichário com ficheiros assinados. Cada peça de informação, é armazenada no seu ficheiro ligada a uma chave. É fácil encontrar um ficheiro através do seu nome, ou adicionar/remover um ficheiro. ![](object.svg) -An empty object ("empty cabinet") can be created using one of two syntaxes: +Um objeto vazio ("fichário vazio"), pode ser criado por uma de duas sintaxes: ```js -let user = new Object(); // "object constructor" syntax -let user = {}; // "object literal" syntax +let user = new Object(); // sintaxe de "construtor de objetos" +let user = {}; // sintaxe de "objeto literal" ``` ![](object-user-empty.svg) -Usually, the figure brackets `{...}` are used. That declaration is called an *object literal*. +Geralmente, são utilizadas as chavetas `{...}`. Essa declaração é chamada de *objeto literal*. -## Literals and properties +## Literais e propriedades -We can immediately put some properties into `{...}` as "key: value" pairs: +Podemos imediatamente colocar algumas propriedades dentro das `{...}` como pares "chave: valor" (*key: value*): ```js -let user = { // an object - name: "John", // by key "name" store value "John" - age: 30 // by key "age" store value 30 +let user = { // um objeto + name: "John", // na chave "name" armazene o valor "John" + age: 30 // na chave "age" armazene o valor 30 }; ``` -A property has a key (also known as "name" or "identifier") before the colon `":"` and a value to the right of it. +Uma propriedade, tem uma chave (*key* - também conhecida por "nome" ou "identificador") antes dos dois-pontos `":"` e um valor à sua direita. -In the `user` object, there are two properties: +No objeto `user`, existem duas propriedades: -1. The first property has the name `"name"` and the value `"John"`. -2. The second one has the name `"age"` and the value `30`. +1. A primeira, tem o nome `"name"` e o valor `"John"`. +2. A segunda, tem o nome `"age"` e o valor `30`. -The resulting `user` object can be imagined as a cabinet with two signed files labeled "name" and "age". +O objeto `user` resultante, pode ser imaginado como um fichário com dois ficheiros assinados com as etiquetas "*name*" e "*age*". ![user object](object-user.svg) -We can add, remove and read files from it any time. +Podemos adicionar, remover e ler ficheiros dele a qualquer altura. -Property values are accessible using the dot notation: +Valores de propriedades podem ser acedidos usando a notação por ponto (*dot notation*): ```js -// get fields of the object: +// obtenha os campos do objeto: alert( user.name ); // John alert( user.age ); // 30 ``` -The value can be of any type. Let's add a boolean one: +O valor pode ser de qualquer tipo. Vamos adicionar um booleano: ```js user.isAdmin = true; @@ -62,7 +62,7 @@ user.isAdmin = true; ![user object 2](object-user-isadmin.svg) -To remove a property, we can use `delete` operator: +Para remover uma propriedade, podemos usar o operador `delete`: ```js delete user.age; @@ -70,69 +70,70 @@ delete user.age; ![user object 3](object-user-delete.svg) -We can also use multiword property names, but then they must be quoted: +Podemos também usar nomes de propriedades com múltiplas palavras, mas aí eles têm de estar entre aspas: ```js let user = { name: "John", age: 30, - "likes birds": true // multiword property name must be quoted + "likes birds": true // "likes birds" ("gosta de pássaros") - o nome de propriedade com múltiplas palavras tem de estar entre aspas }; ``` ![](object-user-props.svg) +A última propriedade da lista pode terminar com uma vírgula: -The last property in the list may end with a comma: ```js let user = { name: "John", age: 30*!*,*/!* } ``` -That is called a "trailing" or "hanging" comma. Makes it easier to add/remove/move around properties, because all lines become alike. -## Square brackets +Esta é chamada de vírgula à direita (*trailing comma*) ou "vírgula pendurada" (*hanging comma*). Ela facilita o adicionar/remover/mover propriedades, porque todas as linhas serão semelhantes (as propriedades são separadas por vírgulas). -For multiword properties, the dot access doesn't work: +## Parênteses retos + +Para propriedades com múltiplas palavras, o acesso por ponto não funciona: ```js run -// this would give a syntax error +// isto daria um erro de sintaxe user.likes birds = true ``` -That's because the dot requires the key to be a valid variable identifier. That is: no spaces and other limitations. +Isto, porque o ponto requere que a chave (*key*) seja um identificador de variável válido. Isto é: sem espaços e outras restrições. -There's an alternative "square bracket notation" that works with any string: +Existe uma alternativa, a "notação por parênteses retos", que funciona com qualquer *string* (cadeia-de-carateres): ```js run let user = {}; -// set +// cria user["likes birds"] = true; -// get -alert(user["likes birds"]); // true +// lê +alert(user["likes birds"]); // true ('verdadeiro') -// delete +// remove delete user["likes birds"]; ``` -Now everything is fine. Please note that the string inside the brackets is properly quoted (any type of quotes will do). +Agora, tudo está bem. Por favor, verifique se a *string* dentro dos parênteses retos está própriamente encerrada entre aspas (qualquer tipo de aspas serve). -Square brackets also provide a way to obtain the property name as the result of any expression -- as opposed to a literal string -- like from a variable as follows: +Os parênteses retos, também fornecem uma forma de se obter o nome de uma propriedade como resultado de uma expressão -- em vez de uma *string* literal -- como a partir de uma variável, a exemplo: ```js let key = "likes birds"; -// same as user["likes birds"] = true; +// o mesmo que 'user["likes birds"] = true;' user[key] = true; ``` -Here, the variable `key` may be calculated at run-time or depend on the user input. And then we use it to access the property. That gives us a great deal of flexibility. The dot notation cannot be used in a similar way. +Aqui, a variável `key` pode ser calculada em tempo de execução (*run-time*) ou depender de uma entrada pelo utilizador (*user input*). E depois a utilizamos para aceder à propriedade. Isso, dá-nos um grande grau de flexibilidade. -For instance: +Por exemplo: ```js run let user = { @@ -140,15 +141,13 @@ let user = { age: 30 }; -let key = prompt("What do you want to know about the user?", "name"); +let key = prompt("O que quer saber acerca do utilizador?", "name"); -// access by variable -alert( user[key] ); // John (if enter "name") +// aceda à variável +alert( user[key] ); // John (se a entrada tiver sido "name") ``` -<<<<<<< HEAD -======= -The dot notation cannot be used in a similar way: +A notação por ponto não pode ser usada de forma semelhante: ```js run let user = { @@ -159,42 +158,41 @@ let user = { let key = "name"; alert( user.key ) // undefined ``` ->>>>>>> 852ee189170d9022f67ab6d387aeae76810b5923 -### Computed properties +### Propriedades computadas -We can use square brackets in an object literal. That's called *computed properties*. +Podemos utilizar os parênteses retos num object literal. Chamam-se de *propriedades computadas*. -For instance: +Por exemplo: ```js run -let fruit = prompt("Which fruit to buy?", "apple"); +let fruit = prompt("Que fruta comprar?", "apple"); let bag = { *!* - [fruit]: 5, // the name of the property is taken from the variable fruit + [fruit]: 5, // o nome da propriedade é obtido por meio da variável 'fruit' */!* }; alert( bag.apple ); // 5 if fruit="apple" ``` -The meaning of a computed property is simple: `[fruit]` means that the property name should be taken from `fruit`. +O significado de uma propriedade computada é simples: `[fruit]` diz que o nome da propriedade é obtido por meio de `fruit`. -So, if a visitor enters `"apple"`, `bag` will become `{apple: 5}`. +Assim, se um visitante inserir `"apple"`, `bag` se tornará em `{apple: 5}`. -Essentially, that works the same as: +Essencialmente, isso é o mesmo que: ```js run -let fruit = prompt("Which fruit to buy?", "apple"); +let fruit = prompt("Que fruta comprar?", "apple"); let bag = {}; -// take property name from the fruit variable +// obtenha o nome da propriedade por meio da variável fruit bag[fruit] = 5; ``` -...But looks nicer. +...Mas, tem uma melhor apresentação. -We can use more complex expressions inside square brackets: +Podemos usar expressões mais complexas dentro dos parênteses retos: ```js let fruit = 'apple'; @@ -203,16 +201,14 @@ let bag = { }; ``` -Square brackets are much more powerful than the dot notation. They allow any property names and variables. But they are also more cumbersome to write. - -So most of the time, when property names are known and simple, the dot is used. And if we need something more complex, then we switch to square brackets. - +Parênteses retos, são mais poderosos que a notação por ponto. Eles permitem quaisquer nomes de propriedades e variáveis. Mas, eles também envolvem mais trabalho para escrever. +Assim, a maior parte as vezes, quando nomes de propriedades são conhecidos e simples, o ponto é utilizado. E, se precisarmos de algo mais complexo, mudamos para os parênteses retos. ````smart header="Reserved words are allowed as property names" -A variable cannot have a name equal to one of language-reserved words like "for", "let", "return" etc. +Uma variável, não pode ter um nome igual a uma das palavras reservadas ('keywords') da linguagem, como "for", "let", "return" etc. -But for an object property, there's no such restriction. Any name is fine: +Mas, para uma propriedade de um objeto, não existe tal restrição. Qualquer nome é aceitável: ```js run let obj = { @@ -224,28 +220,27 @@ let obj = { alert( obj.for + obj.let + obj.return ); // 6 ``` -Basically, any name is allowed, but there's a special one: `"__proto__"` that gets special treatment for historical reasons. For instance, we can't set it to a non-object value: +Basicamente, qualquer nome é permitido, mas existe um especial: `"__proto__"`, que tem um tratamento particular por razões históricas. Por exemplo, a ele não podemos atribuir um valor não-objeto: ```js run let obj = {}; obj.__proto__ = 5; -alert(obj.__proto__); // [object Object], didn't work as intended +alert(obj.__proto__); // [object Object], não resultou como esperado ``` -As we see from the code, the assignment to a primitive `5` is ignored. +Como vemos pelo código, a atribuição do primitivo `5` é ignorada. -That can become a source of bugs and even vulnerabilities if we intend to store arbitrary key-value pairs in an object, and allow a visitor to specify the keys. +Isso, pode se tornar numa fonte de erros ('bugs') e até de vulnerabilidades, se pretendermos armazenar pares chave-valor arbitrários num objeto, e permitir a um visitante especificar as chaves ('keys'). -In that case the visitor may choose "__proto__" as the key, and the assignment logic will be ruined (as shown above). +Nesse caso, o the visitante pode escolher "__proto__" como chave, e a lógica de atribuição estará arruinada (como se mostra acima). -There is a way to make objects treat `__proto__` as a regular property, which we'll cover later, but first we need to know more about objects. -There's also another data structure [Map](info:map-set-weakmap-weakset), that we'll learn in the chapter , which supports arbitrary keys. +Existe uma forma de fazer os objetos tratarem `__proto__` como uma propriedade regular, que analisaremos mais adiante, mas primeiro precisamos de saber mais sobre objetos. +Existe também outra estrutura de dados [Map](info:map-set-weakmap-weakset), que aprenderemos no capítulo , que suporta chaves arbitrárias. ```` +## Abreviação do valor da propriedade -## Property value shorthand - -In real code we often use existing variables as values for property names. +Em código real, frequentemente empregamos variáveis semelhantes a valores como nomes de propriedades. For instance: @@ -254,7 +249,7 @@ function makeUser(name, age) { return { name: name, age: age - // ...other properties + // ...outras propriedades }; } @@ -262,103 +257,102 @@ let user = makeUser("John", 30); alert(user.name); // John ``` -In the example above, properties have the same names as variables. The use-case of making a property from a variable is so common, that there's a special *property value shorthand* to make it shorter. +No exemplo acima, propriedades têm os mesmos nomes que as variáveis. O caso prático (*use-case*) de construir uma propriedade com base numa variável é tão comum, que existe uma especial *abreviação do valor da propriedade* (*property value shorthand*) para a tornar mais curta. -Instead of `name:name` we can just write `name`, like this: +Em vez de `name:name`, podemos simplesmente escrever `name`, como abaixo: ```js function makeUser(name, age) { *!* return { - name, // same as name: name - age // same as age: age + name, // o mesmo que name: name + age // o mesmo que age: age // ... }; */!* } ``` -We can use both normal properties and shorthands in the same object: +Podemos empregar ambas, as propriedades normais e as abreviações (*shorthands*) no mesmo objeto: ```js let user = { - name, // same as name:name + name, // o mesmo que name:name age: 30 }; ``` -## Existence check +## Verificação de existência -A notable objects feature is that it's possible to access any property. There will be no error if the property doesn't exist! Accessing a non-existing property just returns `undefined`. It provides a very common way to test whether the property exists -- to get it and compare vs undefined: +Uma particularidade notável de objetos, é que é possível aceder a qualquer propriedade. Não haverá erro se a propriedade não existir! Aceder a uma propriedade não-existente apenas retorna `undefined`. Ela, fornece uma forma muito comum de testar se a propriedade existe -- aceda, e compare o resultado com *undefined*: ```js run let user = {}; -alert( user.noSuchProperty === undefined ); // true means "no such property" +alert( user.noSuchProperty === undefined ); // true, significa "propriedade não existente" (no such property) ``` -There also exists a special operator `"in"` to check for the existence of a property. +Também existe um operador especial, `"in"`, para verificar a existência de uma propriedade. + +A sintaxe é: -The syntax is: ```js "key" in object ``` -For instance: +Por exemplo: ```js run let user = { name: "John", age: 30 }; -alert( "age" in user ); // true, user.age exists -alert( "blabla" in user ); // false, user.blabla doesn't exist +alert( "age" in user ); // true (verdadeiro), 'user.age' existe +alert( "blabla" in user ); // false (falso), 'user.blabla' não existe ``` -Please note that on the left side of `in` there must be a *property name*. That's usually a quoted string. +Por favor, note que no lado esquerdo de `in` deve existir um *nome de propriedade*. Geralmente, é uma *string* entre aspas. -If we omit quotes, that would mean a variable containing the actual name will be tested. For instance: +Se omitirmos as aspas, isso terá o significado de uma variável contendo o atual nome a ser testado. Por exemplo: ```js run let user = { age: 30 }; let key = "age"; -alert( *!*key*/!* in user ); // true, takes the name from key and checks for such property +alert( *!*key*/!* in user ); // true (verdadeiro), recebe o nome por meio de 'key' e procura por tal propriedade ``` -````smart header="Using \"in\" for properties that store `undefined`" -Usually, the strict comparison `"=== undefined"` check works fine. But there's a special case when it fails, but `"in"` works correctly. +````smart header="Using "in" for properties that store "undefined"" +Geralmente, a comparação exata ('strict') para a verificação `"=== undefined"` funciona bem. Mas, existe um caso especial em que falha. Contudo, `"in"` funciona corretamente. -It's when an object property exists, but stores `undefined`: +É quando uma propriedade de um objeto existe, mas possui `undefined` nela armazenado: ```js run let obj = { test: undefined }; -alert( obj.test ); // it's undefined, so - no such property? +alert( obj.test ); // exibe 'undefined', então - tal propriedade não existe? -alert( "test" in obj ); // true, the property does exist! +alert( "test" in obj ); // true (verdadeiro), a propriedade na realidade existe! ``` +No código acima, a propriedade `obj.test` tecnicamente existe. Deste modo, o operador `in` funciona corretamente. -In the code above, the property `obj.test` technically exists. So the `in` operator works right. - -Situations like this happen very rarely, because `undefined` is usually not assigned. We mostly use `null` for "unknown" or "empty" values. So the `in` operator is an exotic guest in the code. +Situações como esta muito raramente ocorrem, porque `undefined` não é usualmente atribuido. Em geral, empregamos `null` para valores "desconhecidos" ou "vazios". Deste modo, o operador `in` é um convidado exótico na codificação. ```` +## O laço "for..in" -## The "for..in" loop +Para navegar por todas as chaves (*keys*) de um objeto, existe uma forma especial de laço (*loop*): `for..in`. Esta, é uma construção completamente diferente da do `for(;;)`, que estudámos antes. -To walk over all keys of an object, there exists a special form of the loop: `for..in`. This is a completely different thing from the `for(;;)` construct that we studied before. - -The syntax: +A sintaxe: ```js for (key in object) { - // executes the body for each key among object properties + // executa o corpo do laço, por cada chave (key) de entre as propriedades do objeto } ``` -For instance, let's output all properties of `user`: +Por exemplo, vamos imprimir todas propriedades de `user`: ```js run let user = { @@ -368,33 +362,32 @@ let user = { }; for (let key in user) { - // keys - alert( key ); // name, age, isAdmin - // values for the keys + // key (chave) + alert( key ); // 'name', 'age', isAdmin' + // valor por chave (key) alert( user[key] ); // John, 30, true } ``` -Note that all "for" constructs allow us to declare the looping variable inside the loop, like `let key` here. - -Also, we could use another variable name here instead of `key`. For instance, `"for (let prop in obj)"` is also widely used. +Note, que todas as construções "for" permitem-nos declarar a variável do laço dentro do ciclo (*loop*), como `let key` aqui. +De igual modo, poderíamos usar aqui um nome de variável differente de `key`. Por exemplo, `"for (let prop in obj)"` também é largamente utilizado. -### Ordered like an object +### Ordenado como um objeto -Are objects ordered? In other words, if we loop over an object, do we get all properties in the same order they were added? Can we rely on this? +Os objetos são ordenados? Por outras palavras, se percorrermos um objeto com um laço, será que obtemos todas as propriedades pela mesma ordem em que foram adicionadas? Poderemos confiar nisso? -The short answer is: "ordered in a special fashion": integer properties are sorted, others appear in creation order. The details follow. +A curta resposta é: "ordenados de um modo especial" - propriedades inteiras são ordenadas de forma crescente, outras aparecem na ordem em que foram criadas. Detalhes a seguir. -As an example, let's consider an object with the phone codes: +Como exemplo, considermos um objeto com indicativos telefónicos de países: ```js run let codes = { - "49": "Germany", - "41": "Switzerland", - "44": "Great Britain", + "49": "Alemanha", + "41": "Suíça", + "44": "Grã Bretanha", // .., - "1": "USA" + "1": "EUA" }; *!* @@ -404,56 +397,59 @@ for (let code in codes) { */!* ``` -The object may be used to suggest a list of options to the user. If we're making a site mainly for German audience then we probably want `49` to be the first. +O objeto, pode ser empregue como sugestão de uma lista de opções para o utilizador. Se, estivermos a construir um *site* maioritariamente para uma audiência Alemã, então provavelmente queremos `49` como o primeiro. -But if we run the code, we see a totally different picture: +Mas, ao correr o código, vemos uma imagem totalmente diferente: -- USA (1) goes first -- then Switzerland (41) and so on. +- EUA (1) vem em primeiro lugar, +- depois a Suiça (41), e assim por adiante. -The phone codes go in the ascending sorted order, because they are integers. So we see `1, 41, 44, 49`. +Os indicativos telefónicos, são ordenados por ordem ascendente, porque são inteiros. Por isso, vemos `1, 41, 44, 49`. ````smart header="Integer properties? What's that?" -The "integer property" term here means a string that can be converted to-and-from an integer without a change. +O termo "propriedade inteira" aqui, significa que uma *string* pode ser convertida para inteiro ('integer') e, de volta reconvertida sem qualquer alteração. -So, "49" is an integer property name, because when it's transformed to an integer number and back, it's still the same. But "+49" and "1.2" are not: +Assim, "49" é um nome de propriedade inteiro porque, ao ser transformado num número inteiro e de volta reconvertido, continua o mesmo. Mas, "+49" e "1.2" não são: ```js run -// Math.trunc is a built-in function that removes the decimal part -alert( String(Math.trunc(Number("49"))) ); // "49", same, integer property -alert( String(Math.trunc(Number("+49"))) ); // "49", not same "+49" ⇒ not integer property -alert( String(Math.trunc(Number("1.2"))) ); // "1", not same "1.2" ⇒ not integer property +// Math.trunc é uma função incorporada (*built-in function*) que remove a parte decimal + +alert( String(Math.trunc(Number("49"))) ); // "49", inalterado ⇒ propriedade inteira + +alert( String(Math.trunc(Number("+49"))) ); // "49", não o mesmo que "+49" ⇒ não é uma propriedade inteira + +alert( String(Math.trunc(Number("1.2"))) ); // "1", não o mesmo que "1.2" ⇒ não é uma propriedade inteira ``` ```` -...On the other hand, if the keys are non-integer, then they are listed in the creation order, for instance: +...Por outro lado, se as chaves (*keys*) forem não-inteiras, elas são listadas segundo a ordem em que foram criadas, por exemplo: ```js run let user = { name: "John", surname: "Smith" }; -user.age = 25; // add one more +user.age = 25; // adicione mais uma propriedade *!* -// non-integer properties are listed in the creation order +// propriedades não-inteiras são listadas segundo a ordem em que foram criadas */!* for (let prop in user) { - alert( prop ); // name, surname, age + alert( prop ); // 'name', 'surname', 'age' } ``` -So, to fix the issue with the phone codes, we can "cheat" by making the codes non-integer. Adding a plus `"+"` sign before each code is enough. +Portanto, para corrigir o problema dos indicativos telefónicos, podemos "aldrabar" tornando-os não-inteiros. Adicionar um sinal de mais `"+"`, antes de cada código é o suficiente. -Like this: +Desta forma: ```js run let codes = { - "+49": "Germany", - "+41": "Switzerland", - "+44": "Great Britain", + "+49": "Alemanha", + "+41": "Suiça", + "+44": "Grã Bretanha", // .., - "+1": "USA" + "+1": "EUA" }; for (let code in codes) { @@ -461,30 +457,30 @@ for (let code in codes) { } ``` -Now it works as intended. +Agora, funciona como pretendido. -## Copying by reference +## Cópia por referência -One of the fundamental differences of objects vs primitives is that they are stored and copied "by reference". +Uma das principais diferenças entre objetos vs primitivos, está em que os primeiros são armazenados e copiados "por referência" (*by reference*). -Primitive values: strings, numbers, booleans -- are assigned/copied "as a whole value". +Valores primitivos: *strings*, números, booleanos -- são atribuidos/copiados como "o próprio valor". -For instance: +Por exemplo: ```js let message = "Hello!"; let phrase = message; ``` -As a result we have two independent variables, each one is storing the string `"Hello!"`. +Como resultado, temos duas variáveis independentes, mas cada uma armazenando a *string* (cadeia-de-carateres) `"Hello!"`. ![](variable-copy-value.svg) -Objects are not like that. +Objetos não são assim. -**A variable stores not the object itself, but its "address in memory", in other words "a reference" to it.** +**Uma variável não armazena o próprio objeto, mas o seu "endereço em memória" (*address in memory*), por outras palavras "uma referência" (*reference*) a ele.** -Here's the picture for the object: +Aqui, está a imagem para o objeto: ```js let user = { @@ -494,25 +490,25 @@ let user = { ![](variable-contains-reference.svg) -Here, the object is stored somewhere in memory. And the variable `user` has a "reference" to it. +Aqui, o objeto é armazenado algures na memória. E a variável `user` contém uma "referência" para ele. -**When an object variable is copied -- the reference is copied, the object is not duplicated.** +**Quando uma variável com um objeto é copiada -- é a referência copiada, o objeto não é duplicado.** -If we imagine an object as a cabinet, then a variable is a key to it. Copying a variable duplicates the key, but not the cabinet itself. +Se imaginarmos um objeto como um fichário, então uma variável será uma chave (*a key*) para ele. Copiando uma variável duplica a chave (*the key*), não o próprio fichário. -For instance: +Por exemplo: ```js no-beautify let user = { name: "John" }; -let admin = user; // copy the reference +let admin = user; // copia a referência ``` -Now we have two variables, each one with the reference to the same object: +Agora, temos duas variáveis, e cada uma com a referência para o mesmo objeto: ![](variable-copy-reference.svg) -We can use any variable to access the cabinet and modify its contents: +Podemos utilizar qualquer das variáveis, para aceder ao fichário e alterar o seu conteúdo: ```js run let user = { name: 'John' }; @@ -520,46 +516,46 @@ let user = { name: 'John' }; let admin = user; *!* -admin.name = 'Pete'; // changed by the "admin" reference +admin.name = 'Pete'; // alterado através da referência em "admin" */!* -alert(*!*user.name*/!*); // 'Pete', changes are seen from the "user" reference +alert(*!*user.name*/!*); // 'Pete', as alterações também são visíveis por meio da referência em "user" ``` -The example above demonstrates that there is only one object. As if we had a cabinet with two keys and used one of them (`admin`) to get into it. Then, if we later use the other key (`user`) we would see changes. +O exemplo acima, demonstra que apenas existe um objecto. Como se tivéssemos um fichário com duas chaves, e usássemos uma delas (`admin`) para o aceder. E depois, se mais tarde usássemos a outra chave (`user`) poderíamos ver as alterações. -### Comparison by reference +### Comparação por referência -The equality `==` and strict equality `===` operators for objects work exactly the same. +Os operadores de igualdade `==` e de igualdade exata (*strict*) `===` para objetos funcionam exatamente da mesma forma. -**Two objects are equal only if they are the same object.** +**Dois objetos apenas são iguais se eles forem o mesmo objeto.** -For instance, two variables reference the same object, they are equal: +Por exemplo, duas variáveis referenciam o mesmo objeto, elas são iguais: ```js run let a = {}; -let b = a; // copy the reference +let b = a; // cópia por referência -alert( a == b ); // true, both variables reference the same object -alert( a === b ); // true +alert( a == b ); // true (verdadeiro), ambas as variáveis referenciam o mesmo objeto +alert( a === b ); // true (verdadeiro) ``` -And here two independent objects are not equal, even though both are empty: +E aqui, dois objetos independentes não são iguais, muito embora ambos sejam vazios: ```js run let a = {}; -let b = {}; // two independent objects +let b = {}; // dois objetos independentes -alert( a == b ); // false +alert( a == b ); // false (falso) ``` -For comparisons like `obj1 > obj2` or for a comparison against a primitive `obj == 5`, objects are converted to primitives. We'll study how object conversions work very soon, but to tell the truth, such comparisons are necessary very rarely and usually are a result of a coding mistake. +Para comparações como `obj1 > obj2` ou para uma comparação com um primitivo `obj == 5`, objetos são convertidos para primitivos. Estudaremos como funciona a conversão de objetos muito em breve, mas para dizer a verdade, tais comparações são muito raramente necessárias e são geralmente o resultado de um erro de código. -### Const object +### Objeto constante -An object declared as `const` *can* be changed. +Um objeto declarado com `const` *pode* ser alterado. -For instance: +Por exemplo: ```js run const user = { @@ -573,9 +569,9 @@ user.age = 25; // (*) alert(user.age); // 25 ``` -It might seem that the line `(*)` would cause an error, but no, there's totally no problem. That's because `const` fixes the value of `user` itself. And here `user` stores the reference to the same object all the time. The line `(*)` goes *inside* the object, it doesn't reassign `user`. +Parece que a linha `(*)` irá causar um erro, mas não, não há totalmente qualquer problema. Isso, porque `const` apenas fixa o valor de `user`. Então, aqui `user` armazena uma referência para um mesmo objeto pelo tempo todo. A linha `(*)` vai para *dentro* do objeto, não faz uma re-atribuição a `user`. -The `const` would give an error if we try to set `user` to something else, for instance: +A `const` produzirá um erro se tentarmos colocar em `user` qualquer outra coisa, por exemplo: ```js run const user = { @@ -583,26 +579,26 @@ const user = { }; *!* -// Error (can't reassign user) +// Erro (não é possível reatribuir a 'user') */!* user = { name: "Pete" }; ``` -...But what if we want to make constant object properties? So that `user.age = 25` would give an error. That's possible too. We'll cover it in the chapter . +...Mas, se quisermos tornar as propriedades do objeto constantes? Então, aí `user.age = 25` produzirá um erro. Isso, também é possível. Iremos cobrir isto no capítulo . -## Cloning and merging, Object.assign +## Clonar e fundir, Object.assign -So, copying an object variable creates one more reference to the same object. +Portanto, a cópia de uma variável de objeto cria mais uma referência para o mesmo objeto. -But what if we need to duplicate an object? Create an independent copy, a clone? +Mas, se quisermos duplicar um objecto? Criar uma cópia independente, um *clone*? -That's also doable, but a little bit more difficult, because there's no built-in method for that in JavaScript. Actually, that's rarely needed. Copying by reference is good most of the time. +Também se pode fazer, mas é um pouco mais difícil, porque não existe método incorporado (*built-in*) ao JavaScript para isso. Na verdade, isso raramente é necessário. A cópia por referência é a maior parte das vezes boa. -But if we really want that, then we need to create a new object and replicate the structure of the existing one by iterating over its properties and copying them on the primitive level. +Mas, se realmente quisermos isto, aí precisaremos de criar um novo objeto e replicar a estrutura do existente iterando pelas suas propriedades e copiando-as, digamos num nível primitivo. -Like this: +Desta forma: ```js run let user = { @@ -611,32 +607,32 @@ let user = { }; *!* -let clone = {}; // the new empty object +let clone = {}; // o novo objeto vazio -// let's copy all user properties into it +// copiemos todas as propriedades de 'user' para aquele for (let key in user) { clone[key] = user[key]; } */!* -// now clone is a fully independent clone -clone.name = "Pete"; // changed the data in it +// agora,'clone' é um clone completamente independente +clone.name = "Pete"; // altere dados nele -alert( user.name ); // still John in the original object +alert( user.name ); // contudo, ainda está 'John' no objeto original ``` -Also we can use the method [Object.assign](mdn:js/Object/assign) for that. +Podemos também empregar o método [Object.assign](mdn:js/Object/assign) para isso. -The syntax is: +A sintaxe é: ```js Object.assign(dest, [src1, src2, src3...]) ``` -- Arguments `dest`, and `src1, ..., srcN` (can be as many as needed) are objects. -- It copies the properties of all objects `src1, ..., srcN` into `dest`. In other words, properties of all arguments starting from the 2nd are copied into the 1st. Then it returns `dest`. +- Os argumentos `dest`, e `src1, ..., srcN` (que podem ser tantos quantos necessários) são objetos. +- Ele copia as propriedades de todos os objects `src1, ..., srcN` para `dest`. Por outras palavras, propriedades de todos os objetos, a começar pelo segundo, são copiadas para o primeiro. Depois, ele retorna `dest`. -For instance, we can use it to merge several objects into one: +Por exemplo, podemos utilizá-lo para fundir vários objetos num só: ```js let user = { name: "John" }; @@ -644,25 +640,25 @@ let permissions1 = { canView: true }; let permissions2 = { canEdit: true }; *!* -// copies all properties from permissions1 and permissions2 into user +// copia todas propriedades de 'permissions1' e 'permissions2' para 'user' Object.assign(user, permissions1, permissions2); */!* -// now user = { name: "John", canView: true, canEdit: true } +// agora, user = { name: "John", canView: true, canEdit: true } ``` -If the receiving object (`user`) already has the same named property, it will be overwritten: +Se, o objeto recetor (`user`) já tiver alguma propriedade com o mesmo nome, ela será substituída (*overwritten*): ```js let user = { name: "John" }; -// overwrite name, add isAdmin +// substitua ('overwrite') 'nome', e adicione 'isAdmin' Object.assign(user, { name: "Pete", isAdmin: true }); -// now user = { name: "Pete", isAdmin: true } +// agora, user = { name: "Pete", isAdmin: true } ``` -We also can use `Object.assign` to replace the loop for simple cloning: +Podemos também utilizar `Object.assign` para substituir o ciclo (*loop*) acima para uma clonagem simples: ```js let user = { @@ -675,11 +671,12 @@ let clone = Object.assign({}, user); */!* ``` -It copies all properties of `user` into the empty object and returns it. Actually, the same as the loop, but shorter. +Ele copia todas as propriedades de `user` para o objecto vazio e retorna este. Na verdade, é o mesmo laço (*loop*), mas mais curto. + +Até agora, assumimos que todas as propriedades de `user` são primitivas. Mas, propriedades podem ser referências para outros objetos. O que fazer nesse caso? -Until now we assumed that all properties of `user` are primitive. But properties can be references to other objects. What to do with them? +Como aqui: -Like this: ```js run let user = { name: "John", @@ -692,9 +689,10 @@ let user = { alert( user.sizes.height ); // 182 ``` -Now it's not enough to copy `clone.sizes = user.sizes`, because the `user.sizes` is an object, it will be copied by reference. So `clone` and `user` will share the same sizes: +Agora, não é suficiente efetuar a cópia `clone.sizes = user.sizes`, porque `user.sizes` é um objeto, e aí seria copiado por referência. Então, `clone` e `user` iriam partilhar a mesma propriedade "*sizes*": + +Deste modo: -Like this: ```js run let user = { name: "John", @@ -706,49 +704,48 @@ let user = { let clone = Object.assign({}, user); -alert( user.sizes === clone.sizes ); // true, same object +alert( user.sizes === clone.sizes ); // true (verdadeiro), é o mesmo objeto -// user and clone share sizes -user.sizes.width++; // change a property from one place -alert(clone.sizes.width); // 51, see the result from the other one +// 'user' e 'clone' partilham 'sizes' +user.sizes.width++; // altere uma propriedade num lugar +alert(clone.sizes.width); // 51, e verá o resultado a partir do outro ``` -To fix that, we should use the cloning loop that examines each value of `user[key]` and, if it's an object, then replicate its structure as well. That is called a "deep cloning". - -There's a standard algorithm for deep cloning that handles the case above and more complex cases, called the [Structured cloning algorithm](http://w3c.github.io/html/infrastructure.html#safe-passing-of-structured-data). In order not to reinvent the wheel, we can use a working implementation of it from the JavaScript library [lodash](https://lodash.com), the method is called [_.cloneDeep(obj)](https://lodash.com/docs#cloneDeep). - +Para corrigir isso, deveriamos empregar o laço (*loop*) para clonagem, que examina cada valor de `user[key]` e, se for um objeto, então também replica essa estrutura. Essa, é chamada de uma "clonagem profunda" ("*deep cloning*"). +Existe um algoritmo padrão (*standard*) para clonagem profunda (deep cloning), que trata tanto do caso acima como de mais complexos, chamado de [Structured cloning algorithm](http://w3c.github.io/html/infrastructure.html#safe-passing-of-structured-data) (algoritmo de clonagem de estruturas). Para não se reinventar a roda, poderemos utilizar uma implementação operacional do mesmo disponível na biblioteca (*library*) de JavaScript [lodash](https://lodash.com), o método é chamado [_.cloneDeep(obj)](https://lodash.com/docs#cloneDeep). -## Summary +## Sumário -Objects are associative arrays with several special features. +Objetos são *arrays* associativos (*associative arrays*), com várias funcionalidades especiais. -They store properties (key-value pairs), where: -- Property keys must be strings or symbols (usually strings). -- Values can be of any type. +Eles armazenam propriedades em pares chave-valor, onde: +- As chaves das propriedades devem ser *strings* ou símbolos (geralmente *strings*). +- Valores podem ser de qualquer tipo. -To access a property, we can use: -- The dot notation: `obj.property`. -- Square brackets notation `obj["property"]`. Square brackets allow to take the key from a variable, like `obj[varWithKey]`. +Para aceder a uma propriedade, podemos utilizar: +- A notação por ponto: `obj.property`. +- A notação por parênteses retos `obj["property"]`. Os parênteses retos permitem receber a chave de uma variável, como por exemplo `obj[varWithKey]`. -Additional operators: -- To delete a property: `delete obj.prop`. -- To check if a property with the given key exists: `"key" in obj`. -- To iterate over an object: `for (let key in obj)` loop. +Operadores adicionais: +- Para remover uma propriedade: `delete obj.prop`. +- Para verificar se uma propriedade com uma dada chave existe: `"key" in obj`. +- Para iterar sobre um objeto: o ciclo `for (let key in obj)`. -Objects are assigned and copied by reference. In other words, a variable stores not the "object value", but a "reference" (address in memory) for the value. So copying such a variable or passing it as a function argument copies that reference, not the object. All operations via copied references (like adding/removing properties) are performed on the same single object. +Objetos são atribuidos e copiados por referência. Por outras palavras, uma variável não armazena o "valor do objeto", mas uma "referência" (endereço em memória) do valor. Assim, copiar tal variável ou passá-la como argumento de uma função copia tal referência, não o objeto. Todas as operações sobre cópias de referências (como adicionar/remover propriedades) são executadas sobre um mesmo único objeto. -To make a "real copy" (a clone) we can use `Object.assign` or [_.cloneDeep(obj)](https://lodash.com/docs#cloneDeep). + Para efetuar uma "verdadeira cópia" (um clone), podemos utilizar `Object.assign` ou [_.cloneDeep(obj)](https://lodash.com/docs#cloneDeep). -What we've studied in this chapter is called a "plain object", or just `Object`. +O que estudámos neste capítulo é o chamado "objeto simples" ("*plain object*"), ou simplesmente `Objeto`. -There are many other kinds of objects in JavaScript: +Existem muitos outros tipos de objetos em JavaScript: -- `Array` to store ordered data collections, -- `Date` to store the information about the date and time, -- `Error` to store the information about an error. -- ...And so on. +- `Array` para armazenar coleções de dados ordenadas, +- `Date` para armazenar informação sobre data e tempo, +- `Error` para armazenar informação sobre um erro. +- ...E outros mais. -They have their special features that we'll study later. Sometimes people say something like "Array type" or "Date type", but formally they are not types of their own, but belong to a single "object" data type. And they extend it in various ways. +Eles têm as suas funcionalidades especiais, que estudaremos mais adiante. Por vezes, pessoas dizem algo como "o tipo +Array" ou "o tipo Data" (*Date*), mas formalmente eles não são própriamente tipos, mas pertencem a um único tipo de dados "objeto". E o extendem de várias formas. -Objects in JavaScript are very powerful. Here we've just scratched the surface of a topic that is really huge. We'll be closely working with objects and learning more about them in further parts of the tutorial. +Objetos em JavaScript são muito poderosos. Aqui, apenas tocámos na superfície de um realmente amplo tópico. Iremos, mais especificamente, trabalhar e aprender sobre objetos em futuras partes do tutorial. diff --git a/1-js/04-object-basics/index.md b/1-js/04-object-basics/index.md index d2387aafa..991117d25 100644 --- a/1-js/04-object-basics/index.md +++ b/1-js/04-object-basics/index.md @@ -1 +1 @@ -# Objects: the basics +# Objetos: o básico From e788cff1378d6dcecdfd267c879df2efc0b85d68 Mon Sep 17 00:00:00 2001 From: odsantos Date: Tue, 22 Oct 2019 06:28:04 +0100 Subject: [PATCH 2/3] Revert "translate '01-object' directory files" This reverts commit f3fb7d2927a16e702ac7683957ff2981c86d31c5. --- .../01-object/2-hello-object/solution.md | 2 + .../01-object/2-hello-object/task.md | 14 +- .../01-object/3-is-empty/_js.view/solution.js | 2 +- .../01-object/3-is-empty/_js.view/test.js | 4 +- .../01-object/3-is-empty/solution.md | 2 +- .../01-object/3-is-empty/task.md | 13 +- .../01-object/4-const-object/solution.md | 10 +- .../01-object/4-const-object/task.md | 6 +- .../01-object/5-sum-object/task.md | 8 +- .../8-multiply-numeric/_js.view/source.js | 6 +- .../8-multiply-numeric/_js.view/test.js | 8 +- .../01-object/8-multiply-numeric/task.md | 20 +- 1-js/04-object-basics/01-object/article.md | 473 +++++++++--------- 1-js/04-object-basics/index.md | 2 +- 14 files changed, 289 insertions(+), 281 deletions(-) diff --git a/1-js/04-object-basics/01-object/2-hello-object/solution.md b/1-js/04-object-basics/01-object/2-hello-object/solution.md index dff006076..60083b963 100644 --- a/1-js/04-object-basics/01-object/2-hello-object/solution.md +++ b/1-js/04-object-basics/01-object/2-hello-object/solution.md @@ -1,4 +1,5 @@ + ```js let user = {}; user.name = "John"; @@ -6,3 +7,4 @@ user.surname = "Smith"; user.name = "Pete"; delete user.name; ``` + diff --git a/1-js/04-object-basics/01-object/2-hello-object/task.md b/1-js/04-object-basics/01-object/2-hello-object/task.md index c0e296444..2841a058f 100644 --- a/1-js/04-object-basics/01-object/2-hello-object/task.md +++ b/1-js/04-object-basics/01-object/2-hello-object/task.md @@ -2,13 +2,13 @@ importance: 5 --- -# Olá, objeto +# Hello, object -Escreva o código, uma ação por linha: +Write the code, one line for each action: -1. Crie um objeto vazio (*empty object*) `user`. -2. Adicione a propriedade `name` com o valor `John`. -3. Adicione a propriedade `surname` com o valor `Smith`. -4. Altere o valor de `name` para `Pete`. -5. Remova a propriedade `name` do objeto. +1. Create an empty object `user`. +2. Add the property `name` with the value `John`. +3. Add the property `surname` with the value `Smith`. +4. Change the value of the `name` to `Pete`. +5. Remove the property `name` from the object. diff --git a/1-js/04-object-basics/01-object/3-is-empty/_js.view/solution.js b/1-js/04-object-basics/01-object/3-is-empty/_js.view/solution.js index ca7dc324e..db3283e49 100644 --- a/1-js/04-object-basics/01-object/3-is-empty/_js.view/solution.js +++ b/1-js/04-object-basics/01-object/3-is-empty/_js.view/solution.js @@ -1,6 +1,6 @@ function isEmpty(obj) { for (let key in obj) { - // se o laço começou, existe uma propriedade + // if the loop has started, there is a property return false; } return true; diff --git a/1-js/04-object-basics/01-object/3-is-empty/_js.view/test.js b/1-js/04-object-basics/01-object/3-is-empty/_js.view/test.js index 400577698..4db5efabe 100644 --- a/1-js/04-object-basics/01-object/3-is-empty/_js.view/test.js +++ b/1-js/04-object-basics/01-object/3-is-empty/_js.view/test.js @@ -1,9 +1,9 @@ describe("isEmpty", function() { - it("retorna verdadeiro para um objeto vazio", function() { + it("returns true for an empty object", function() { assert.isTrue(isEmpty({})); }); - it("retorna falso se uma propriedade existir", function() { + it("returns false if a property exists", function() { assert.isFalse(isEmpty({ anything: false })); diff --git a/1-js/04-object-basics/01-object/3-is-empty/solution.md b/1-js/04-object-basics/01-object/3-is-empty/solution.md index 6c328fc39..b876973b5 100644 --- a/1-js/04-object-basics/01-object/3-is-empty/solution.md +++ b/1-js/04-object-basics/01-object/3-is-empty/solution.md @@ -1 +1 @@ -Simplemente, percorra (*loop over*) o objeto e imediatamente `return false` se pelo menos houver uma propriedade. +Just loop over the object and `return false` immediately if there's at least one property. diff --git a/1-js/04-object-basics/01-object/3-is-empty/task.md b/1-js/04-object-basics/01-object/3-is-empty/task.md index a499e6eb7..c438d36a2 100644 --- a/1-js/04-object-basics/01-object/3-is-empty/task.md +++ b/1-js/04-object-basics/01-object/3-is-empty/task.md @@ -2,18 +2,19 @@ importance: 5 --- -# Verifique por vazio (*emptiness*) +# Check for emptiness -Escreva a função `isEmpty(obj)`, que retorna `true` se o objeto não tiver propriedades, e `false` caso contrário. +Write the function `isEmpty(obj)` which returns `true` if the object has no properties, `false` otherwise. + +Should work like that: -Deve assim funcionar: ```js let schedule = {}; -alert( isEmpty(schedule) ); // verdadeiro +alert( isEmpty(schedule) ); // true -schedule["8:30"] = "levante-se"; +schedule["8:30"] = "get up"; -alert( isEmpty(schedule) ); // falso +alert( isEmpty(schedule) ); // false ``` diff --git a/1-js/04-object-basics/01-object/4-const-object/solution.md b/1-js/04-object-basics/01-object/4-const-object/solution.md index 9cb150373..f73c2f92b 100644 --- a/1-js/04-object-basics/01-object/4-const-object/solution.md +++ b/1-js/04-object-basics/01-object/4-const-object/solution.md @@ -1,8 +1,8 @@ -Com certeza, funciona, sem problemas. +Sure, it works, no problem. -A `const` apenas protege a própria variável contra alterações. +The `const` only protects the variable itself from changing. -Por outras palavras, `user` armazena uma referência ao objeto. E não pode ser alterada. Mas, o conteúdo do objeto pode. +In other words, `user` stores a reference to the object. And it can't be changed. But the content of the object can. ```js run const user = { @@ -10,10 +10,10 @@ const user = { }; *!* -// funciona +// works user.name = "Pete"; */!* -// erro +// error user = 123; ``` diff --git a/1-js/04-object-basics/01-object/4-const-object/task.md b/1-js/04-object-basics/01-object/4-const-object/task.md index a0a1709dc..a9aada631 100644 --- a/1-js/04-object-basics/01-object/4-const-object/task.md +++ b/1-js/04-object-basics/01-object/4-const-object/task.md @@ -2,9 +2,9 @@ importance: 5 --- -# Objetos constantes? +# Constant objects? -É possível alterar um objeto declarado com `const`? O que acha? +Is it possible to change an object declared with `const`? What do you think? ```js const user = { @@ -12,7 +12,7 @@ const user = { }; *!* -// isto funciona? +// does it work? user.name = "Pete"; */!* ``` diff --git a/1-js/04-object-basics/01-object/5-sum-object/task.md b/1-js/04-object-basics/01-object/5-sum-object/task.md index b0caee202..7e3e048d0 100644 --- a/1-js/04-object-basics/01-object/5-sum-object/task.md +++ b/1-js/04-object-basics/01-object/5-sum-object/task.md @@ -2,9 +2,9 @@ importance: 5 --- -# Soma das propriedades de um objeto +# Sum object properties -Temos um objeto armazenando salários da nossa equipa: +We have an object storing salaries of our team: ```js let salaries = { @@ -14,6 +14,6 @@ let salaries = { } ``` -Escreva o código para somar todos os salários e armazenar na variável `sum`. Para o exemplo acima, deverá ser `390`. +Write the code to sum all salaries and store in the variable `sum`. Should be `390` in the example above. -Se `salaries` for vazio, então o resultado deve ser `0`. \ No newline at end of file +If `salaries` is empty, then the result must be `0`. \ No newline at end of file diff --git a/1-js/04-object-basics/01-object/8-multiply-numeric/_js.view/source.js b/1-js/04-object-basics/01-object/8-multiply-numeric/_js.view/source.js index f2ffe4901..a02b1e1cb 100644 --- a/1-js/04-object-basics/01-object/8-multiply-numeric/_js.view/source.js +++ b/1-js/04-object-basics/01-object/8-multiply-numeric/_js.view/source.js @@ -1,17 +1,17 @@ let menu = { width: 200, height: 300, - title: "O meu menu" + title: "My menu" }; function multiplyNumeric(obj) { - /* o seu código */ + /* your code */ } multiplyNumeric(menu); -alert( "largura do menu=" + menu.width + " altura=" + menu.height + " título=" + menu.title ); +alert( "menu width=" + menu.width + " height=" + menu.height + " title=" + menu.title ); diff --git a/1-js/04-object-basics/01-object/8-multiply-numeric/_js.view/test.js b/1-js/04-object-basics/01-object/8-multiply-numeric/_js.view/test.js index 2ba28f769..064e5414f 100644 --- a/1-js/04-object-basics/01-object/8-multiply-numeric/_js.view/test.js +++ b/1-js/04-object-basics/01-object/8-multiply-numeric/_js.view/test.js @@ -1,17 +1,17 @@ describe("multiplyNumeric", function() { - it("multiplica todas as propriedades numéricas por 2", function() { + it("multiplies all numeric properties by 2", function() { let menu = { width: 200, height: 300, - title: "O meu menu" + title: "My menu" }; let result = multiplyNumeric(menu); assert.equal(menu.width, 400); assert.equal(menu.height, 600); - assert.equal(menu.title, "O meu menu"); + assert.equal(menu.title, "My menu"); }); - it("não retorna nada", function() { + it("returns nothing", function() { assert.isUndefined( multiplyNumeric({}) ); }); diff --git a/1-js/04-object-basics/01-object/8-multiply-numeric/task.md b/1-js/04-object-basics/01-object/8-multiply-numeric/task.md index 54fa7fceb..33eb89220 100644 --- a/1-js/04-object-basics/01-object/8-multiply-numeric/task.md +++ b/1-js/04-object-basics/01-object/8-multiply-numeric/task.md @@ -2,30 +2,32 @@ importance: 3 --- -# Multiplica as propriedades numéricas por 2 +# Multiply numeric properties by 2 -Crie uma função `multiplyNumeric(obj)` que multiplica todas as proriedades numéricas de `obj` por `2`. +Create a function `multiplyNumeric(obj)` that multiplies all numeric properties of `obj` by `2`. -Por exemplo: +For instance: ```js -// antes da chamada +// before the call let menu = { width: 200, height: 300, - title: "O meu menu" + title: "My menu" }; multiplyNumeric(menu); -// depois da chamada +// after the call menu = { width: 400, height: 600, - title: "O meu menu" + title: "My menu" }; ``` -Por favor, note que `multiplyNumeric` não precisa de retornar nada. Deve modificar o próprio objecto. +Please note that `multiplyNumeric` does not need to return anything. It should modify the object in-place. + +P.S. Use `typeof` to check for a number here. + -P.S. Use `typeof` para verificar por um número aqui. diff --git a/1-js/04-object-basics/01-object/article.md b/1-js/04-object-basics/01-object/article.md index baba98e3a..00706750c 100644 --- a/1-js/04-object-basics/01-object/article.md +++ b/1-js/04-object-basics/01-object/article.md @@ -1,60 +1,60 @@ -# Objetos +# Objects -Como sabemos, pelo capítulo , existem sete tipos de dados em JavaScript. Seis deles são chamados de "primitivos", porque os seus valores apenas contêm uma única coisa (seja ela uma cadeia-de-carateres [*string*], um número, ou o que for). +As we know from the chapter , there are seven data types in JavaScript. Six of them are called "primitive", because their values contain only a single thing (be it a string or a number or whatever). -Em contraste, objetos são empregues para armazenar por meio de uma chave, coleções de vários dados e entidades mais complexas. Em JavaScript, objetos penetram em quase todos os aspetos da linguagem. Portanto, devemos primeiro compreendê-los antes de nos envolvermos detalhadamente em algo mais. +In contrast, objects are used to store keyed collections of various data and more complex entities. In JavaScript, objects penetrate almost every aspect of the language. So we must understand them first before going in-depth anywhere else. -Um objeto pode ser criado por chavetas `{…}`, com uma lista opcional de *propriedades*. Uma propriedade é um par "key: value" (chave: valor), onde `key` é uma *string* (também chamada de "nome da propriedade"), e `value` pode ser qualquer coisa. +An object can be created with figure brackets `{…}` with an optional list of *properties*. A property is a "key: value" pair, where `key` is a string (also called a "property name"), and `value` can be anything. -Podemos imaginar um objeto como um fichário com ficheiros assinados. Cada peça de informação, é armazenada no seu ficheiro ligada a uma chave. É fácil encontrar um ficheiro através do seu nome, ou adicionar/remover um ficheiro. +We can imagine an object as a cabinet with signed files. Every piece of data is stored in its file by the key. It's easy to find a file by its name or add/remove a file. ![](object.svg) -Um objeto vazio ("fichário vazio"), pode ser criado por uma de duas sintaxes: +An empty object ("empty cabinet") can be created using one of two syntaxes: ```js -let user = new Object(); // sintaxe de "construtor de objetos" -let user = {}; // sintaxe de "objeto literal" +let user = new Object(); // "object constructor" syntax +let user = {}; // "object literal" syntax ``` ![](object-user-empty.svg) -Geralmente, são utilizadas as chavetas `{...}`. Essa declaração é chamada de *objeto literal*. +Usually, the figure brackets `{...}` are used. That declaration is called an *object literal*. -## Literais e propriedades +## Literals and properties -Podemos imediatamente colocar algumas propriedades dentro das `{...}` como pares "chave: valor" (*key: value*): +We can immediately put some properties into `{...}` as "key: value" pairs: ```js -let user = { // um objeto - name: "John", // na chave "name" armazene o valor "John" - age: 30 // na chave "age" armazene o valor 30 +let user = { // an object + name: "John", // by key "name" store value "John" + age: 30 // by key "age" store value 30 }; ``` -Uma propriedade, tem uma chave (*key* - também conhecida por "nome" ou "identificador") antes dos dois-pontos `":"` e um valor à sua direita. +A property has a key (also known as "name" or "identifier") before the colon `":"` and a value to the right of it. -No objeto `user`, existem duas propriedades: +In the `user` object, there are two properties: -1. A primeira, tem o nome `"name"` e o valor `"John"`. -2. A segunda, tem o nome `"age"` e o valor `30`. +1. The first property has the name `"name"` and the value `"John"`. +2. The second one has the name `"age"` and the value `30`. -O objeto `user` resultante, pode ser imaginado como um fichário com dois ficheiros assinados com as etiquetas "*name*" e "*age*". +The resulting `user` object can be imagined as a cabinet with two signed files labeled "name" and "age". ![user object](object-user.svg) -Podemos adicionar, remover e ler ficheiros dele a qualquer altura. +We can add, remove and read files from it any time. -Valores de propriedades podem ser acedidos usando a notação por ponto (*dot notation*): +Property values are accessible using the dot notation: ```js -// obtenha os campos do objeto: +// get fields of the object: alert( user.name ); // John alert( user.age ); // 30 ``` -O valor pode ser de qualquer tipo. Vamos adicionar um booleano: +The value can be of any type. Let's add a boolean one: ```js user.isAdmin = true; @@ -62,7 +62,7 @@ user.isAdmin = true; ![user object 2](object-user-isadmin.svg) -Para remover uma propriedade, podemos usar o operador `delete`: +To remove a property, we can use `delete` operator: ```js delete user.age; @@ -70,70 +70,69 @@ delete user.age; ![user object 3](object-user-delete.svg) -Podemos também usar nomes de propriedades com múltiplas palavras, mas aí eles têm de estar entre aspas: +We can also use multiword property names, but then they must be quoted: ```js let user = { name: "John", age: 30, - "likes birds": true // "likes birds" ("gosta de pássaros") - o nome de propriedade com múltiplas palavras tem de estar entre aspas + "likes birds": true // multiword property name must be quoted }; ``` ![](object-user-props.svg) -A última propriedade da lista pode terminar com uma vírgula: +The last property in the list may end with a comma: ```js let user = { name: "John", age: 30*!*,*/!* } ``` +That is called a "trailing" or "hanging" comma. Makes it easier to add/remove/move around properties, because all lines become alike. -Esta é chamada de vírgula à direita (*trailing comma*) ou "vírgula pendurada" (*hanging comma*). Ela facilita o adicionar/remover/mover propriedades, porque todas as linhas serão semelhantes (as propriedades são separadas por vírgulas). +## Square brackets -## Parênteses retos - -Para propriedades com múltiplas palavras, o acesso por ponto não funciona: +For multiword properties, the dot access doesn't work: ```js run -// isto daria um erro de sintaxe +// this would give a syntax error user.likes birds = true ``` -Isto, porque o ponto requere que a chave (*key*) seja um identificador de variável válido. Isto é: sem espaços e outras restrições. +That's because the dot requires the key to be a valid variable identifier. That is: no spaces and other limitations. -Existe uma alternativa, a "notação por parênteses retos", que funciona com qualquer *string* (cadeia-de-carateres): +There's an alternative "square bracket notation" that works with any string: ```js run let user = {}; -// cria +// set user["likes birds"] = true; -// lê -alert(user["likes birds"]); // true ('verdadeiro') +// get +alert(user["likes birds"]); // true -// remove +// delete delete user["likes birds"]; ``` -Agora, tudo está bem. Por favor, verifique se a *string* dentro dos parênteses retos está própriamente encerrada entre aspas (qualquer tipo de aspas serve). +Now everything is fine. Please note that the string inside the brackets is properly quoted (any type of quotes will do). -Os parênteses retos, também fornecem uma forma de se obter o nome de uma propriedade como resultado de uma expressão -- em vez de uma *string* literal -- como a partir de uma variável, a exemplo: +Square brackets also provide a way to obtain the property name as the result of any expression -- as opposed to a literal string -- like from a variable as follows: ```js let key = "likes birds"; -// o mesmo que 'user["likes birds"] = true;' +// same as user["likes birds"] = true; user[key] = true; ``` -Aqui, a variável `key` pode ser calculada em tempo de execução (*run-time*) ou depender de uma entrada pelo utilizador (*user input*). E depois a utilizamos para aceder à propriedade. Isso, dá-nos um grande grau de flexibilidade. +Here, the variable `key` may be calculated at run-time or depend on the user input. And then we use it to access the property. That gives us a great deal of flexibility. The dot notation cannot be used in a similar way. -Por exemplo: +For instance: ```js run let user = { @@ -141,13 +140,15 @@ let user = { age: 30 }; -let key = prompt("O que quer saber acerca do utilizador?", "name"); +let key = prompt("What do you want to know about the user?", "name"); -// aceda à variável -alert( user[key] ); // John (se a entrada tiver sido "name") +// access by variable +alert( user[key] ); // John (if enter "name") ``` -A notação por ponto não pode ser usada de forma semelhante: +<<<<<<< HEAD +======= +The dot notation cannot be used in a similar way: ```js run let user = { @@ -158,41 +159,42 @@ let user = { let key = "name"; alert( user.key ) // undefined ``` +>>>>>>> 852ee189170d9022f67ab6d387aeae76810b5923 -### Propriedades computadas +### Computed properties -Podemos utilizar os parênteses retos num object literal. Chamam-se de *propriedades computadas*. +We can use square brackets in an object literal. That's called *computed properties*. -Por exemplo: +For instance: ```js run -let fruit = prompt("Que fruta comprar?", "apple"); +let fruit = prompt("Which fruit to buy?", "apple"); let bag = { *!* - [fruit]: 5, // o nome da propriedade é obtido por meio da variável 'fruit' + [fruit]: 5, // the name of the property is taken from the variable fruit */!* }; alert( bag.apple ); // 5 if fruit="apple" ``` -O significado de uma propriedade computada é simples: `[fruit]` diz que o nome da propriedade é obtido por meio de `fruit`. +The meaning of a computed property is simple: `[fruit]` means that the property name should be taken from `fruit`. -Assim, se um visitante inserir `"apple"`, `bag` se tornará em `{apple: 5}`. +So, if a visitor enters `"apple"`, `bag` will become `{apple: 5}`. -Essencialmente, isso é o mesmo que: +Essentially, that works the same as: ```js run -let fruit = prompt("Que fruta comprar?", "apple"); +let fruit = prompt("Which fruit to buy?", "apple"); let bag = {}; -// obtenha o nome da propriedade por meio da variável fruit +// take property name from the fruit variable bag[fruit] = 5; ``` -...Mas, tem uma melhor apresentação. +...But looks nicer. -Podemos usar expressões mais complexas dentro dos parênteses retos: +We can use more complex expressions inside square brackets: ```js let fruit = 'apple'; @@ -201,14 +203,16 @@ let bag = { }; ``` -Parênteses retos, são mais poderosos que a notação por ponto. Eles permitem quaisquer nomes de propriedades e variáveis. Mas, eles também envolvem mais trabalho para escrever. +Square brackets are much more powerful than the dot notation. They allow any property names and variables. But they are also more cumbersome to write. + +So most of the time, when property names are known and simple, the dot is used. And if we need something more complex, then we switch to square brackets. + -Assim, a maior parte as vezes, quando nomes de propriedades são conhecidos e simples, o ponto é utilizado. E, se precisarmos de algo mais complexo, mudamos para os parênteses retos. ````smart header="Reserved words are allowed as property names" -Uma variável, não pode ter um nome igual a uma das palavras reservadas ('keywords') da linguagem, como "for", "let", "return" etc. +A variable cannot have a name equal to one of language-reserved words like "for", "let", "return" etc. -Mas, para uma propriedade de um objeto, não existe tal restrição. Qualquer nome é aceitável: +But for an object property, there's no such restriction. Any name is fine: ```js run let obj = { @@ -220,27 +224,28 @@ let obj = { alert( obj.for + obj.let + obj.return ); // 6 ``` -Basicamente, qualquer nome é permitido, mas existe um especial: `"__proto__"`, que tem um tratamento particular por razões históricas. Por exemplo, a ele não podemos atribuir um valor não-objeto: +Basically, any name is allowed, but there's a special one: `"__proto__"` that gets special treatment for historical reasons. For instance, we can't set it to a non-object value: ```js run let obj = {}; obj.__proto__ = 5; -alert(obj.__proto__); // [object Object], não resultou como esperado +alert(obj.__proto__); // [object Object], didn't work as intended ``` -Como vemos pelo código, a atribuição do primitivo `5` é ignorada. +As we see from the code, the assignment to a primitive `5` is ignored. -Isso, pode se tornar numa fonte de erros ('bugs') e até de vulnerabilidades, se pretendermos armazenar pares chave-valor arbitrários num objeto, e permitir a um visitante especificar as chaves ('keys'). +That can become a source of bugs and even vulnerabilities if we intend to store arbitrary key-value pairs in an object, and allow a visitor to specify the keys. -Nesse caso, o the visitante pode escolher "__proto__" como chave, e a lógica de atribuição estará arruinada (como se mostra acima). +In that case the visitor may choose "__proto__" as the key, and the assignment logic will be ruined (as shown above). -Existe uma forma de fazer os objetos tratarem `__proto__` como uma propriedade regular, que analisaremos mais adiante, mas primeiro precisamos de saber mais sobre objetos. -Existe também outra estrutura de dados [Map](info:map-set-weakmap-weakset), que aprenderemos no capítulo , que suporta chaves arbitrárias. +There is a way to make objects treat `__proto__` as a regular property, which we'll cover later, but first we need to know more about objects. +There's also another data structure [Map](info:map-set-weakmap-weakset), that we'll learn in the chapter , which supports arbitrary keys. ```` -## Abreviação do valor da propriedade -Em código real, frequentemente empregamos variáveis semelhantes a valores como nomes de propriedades. +## Property value shorthand + +In real code we often use existing variables as values for property names. For instance: @@ -249,7 +254,7 @@ function makeUser(name, age) { return { name: name, age: age - // ...outras propriedades + // ...other properties }; } @@ -257,102 +262,103 @@ let user = makeUser("John", 30); alert(user.name); // John ``` -No exemplo acima, propriedades têm os mesmos nomes que as variáveis. O caso prático (*use-case*) de construir uma propriedade com base numa variável é tão comum, que existe uma especial *abreviação do valor da propriedade* (*property value shorthand*) para a tornar mais curta. +In the example above, properties have the same names as variables. The use-case of making a property from a variable is so common, that there's a special *property value shorthand* to make it shorter. -Em vez de `name:name`, podemos simplesmente escrever `name`, como abaixo: +Instead of `name:name` we can just write `name`, like this: ```js function makeUser(name, age) { *!* return { - name, // o mesmo que name: name - age // o mesmo que age: age + name, // same as name: name + age // same as age: age // ... }; */!* } ``` -Podemos empregar ambas, as propriedades normais e as abreviações (*shorthands*) no mesmo objeto: +We can use both normal properties and shorthands in the same object: ```js let user = { - name, // o mesmo que name:name + name, // same as name:name age: 30 }; ``` -## Verificação de existência +## Existence check -Uma particularidade notável de objetos, é que é possível aceder a qualquer propriedade. Não haverá erro se a propriedade não existir! Aceder a uma propriedade não-existente apenas retorna `undefined`. Ela, fornece uma forma muito comum de testar se a propriedade existe -- aceda, e compare o resultado com *undefined*: +A notable objects feature is that it's possible to access any property. There will be no error if the property doesn't exist! Accessing a non-existing property just returns `undefined`. It provides a very common way to test whether the property exists -- to get it and compare vs undefined: ```js run let user = {}; -alert( user.noSuchProperty === undefined ); // true, significa "propriedade não existente" (no such property) +alert( user.noSuchProperty === undefined ); // true means "no such property" ``` -Também existe um operador especial, `"in"`, para verificar a existência de uma propriedade. - -A sintaxe é: +There also exists a special operator `"in"` to check for the existence of a property. +The syntax is: ```js "key" in object ``` -Por exemplo: +For instance: ```js run let user = { name: "John", age: 30 }; -alert( "age" in user ); // true (verdadeiro), 'user.age' existe -alert( "blabla" in user ); // false (falso), 'user.blabla' não existe +alert( "age" in user ); // true, user.age exists +alert( "blabla" in user ); // false, user.blabla doesn't exist ``` -Por favor, note que no lado esquerdo de `in` deve existir um *nome de propriedade*. Geralmente, é uma *string* entre aspas. +Please note that on the left side of `in` there must be a *property name*. That's usually a quoted string. -Se omitirmos as aspas, isso terá o significado de uma variável contendo o atual nome a ser testado. Por exemplo: +If we omit quotes, that would mean a variable containing the actual name will be tested. For instance: ```js run let user = { age: 30 }; let key = "age"; -alert( *!*key*/!* in user ); // true (verdadeiro), recebe o nome por meio de 'key' e procura por tal propriedade +alert( *!*key*/!* in user ); // true, takes the name from key and checks for such property ``` -````smart header="Using "in" for properties that store "undefined"" -Geralmente, a comparação exata ('strict') para a verificação `"=== undefined"` funciona bem. Mas, existe um caso especial em que falha. Contudo, `"in"` funciona corretamente. +````smart header="Using \"in\" for properties that store `undefined`" +Usually, the strict comparison `"=== undefined"` check works fine. But there's a special case when it fails, but `"in"` works correctly. -É quando uma propriedade de um objeto existe, mas possui `undefined` nela armazenado: +It's when an object property exists, but stores `undefined`: ```js run let obj = { test: undefined }; -alert( obj.test ); // exibe 'undefined', então - tal propriedade não existe? +alert( obj.test ); // it's undefined, so - no such property? -alert( "test" in obj ); // true (verdadeiro), a propriedade na realidade existe! +alert( "test" in obj ); // true, the property does exist! ``` -No código acima, a propriedade `obj.test` tecnicamente existe. Deste modo, o operador `in` funciona corretamente. -Situações como esta muito raramente ocorrem, porque `undefined` não é usualmente atribuido. Em geral, empregamos `null` para valores "desconhecidos" ou "vazios". Deste modo, o operador `in` é um convidado exótico na codificação. +In the code above, the property `obj.test` technically exists. So the `in` operator works right. + +Situations like this happen very rarely, because `undefined` is usually not assigned. We mostly use `null` for "unknown" or "empty" values. So the `in` operator is an exotic guest in the code. ```` -## O laço "for..in" -Para navegar por todas as chaves (*keys*) de um objeto, existe uma forma especial de laço (*loop*): `for..in`. Esta, é uma construção completamente diferente da do `for(;;)`, que estudámos antes. +## The "for..in" loop -A sintaxe: +To walk over all keys of an object, there exists a special form of the loop: `for..in`. This is a completely different thing from the `for(;;)` construct that we studied before. + +The syntax: ```js for (key in object) { - // executa o corpo do laço, por cada chave (key) de entre as propriedades do objeto + // executes the body for each key among object properties } ``` -Por exemplo, vamos imprimir todas propriedades de `user`: +For instance, let's output all properties of `user`: ```js run let user = { @@ -362,32 +368,33 @@ let user = { }; for (let key in user) { - // key (chave) - alert( key ); // 'name', 'age', isAdmin' - // valor por chave (key) + // keys + alert( key ); // name, age, isAdmin + // values for the keys alert( user[key] ); // John, 30, true } ``` -Note, que todas as construções "for" permitem-nos declarar a variável do laço dentro do ciclo (*loop*), como `let key` aqui. +Note that all "for" constructs allow us to declare the looping variable inside the loop, like `let key` here. + +Also, we could use another variable name here instead of `key`. For instance, `"for (let prop in obj)"` is also widely used. -De igual modo, poderíamos usar aqui um nome de variável differente de `key`. Por exemplo, `"for (let prop in obj)"` também é largamente utilizado. -### Ordenado como um objeto +### Ordered like an object -Os objetos são ordenados? Por outras palavras, se percorrermos um objeto com um laço, será que obtemos todas as propriedades pela mesma ordem em que foram adicionadas? Poderemos confiar nisso? +Are objects ordered? In other words, if we loop over an object, do we get all properties in the same order they were added? Can we rely on this? -A curta resposta é: "ordenados de um modo especial" - propriedades inteiras são ordenadas de forma crescente, outras aparecem na ordem em que foram criadas. Detalhes a seguir. +The short answer is: "ordered in a special fashion": integer properties are sorted, others appear in creation order. The details follow. -Como exemplo, considermos um objeto com indicativos telefónicos de países: +As an example, let's consider an object with the phone codes: ```js run let codes = { - "49": "Alemanha", - "41": "Suíça", - "44": "Grã Bretanha", + "49": "Germany", + "41": "Switzerland", + "44": "Great Britain", // .., - "1": "EUA" + "1": "USA" }; *!* @@ -397,59 +404,56 @@ for (let code in codes) { */!* ``` -O objeto, pode ser empregue como sugestão de uma lista de opções para o utilizador. Se, estivermos a construir um *site* maioritariamente para uma audiência Alemã, então provavelmente queremos `49` como o primeiro. +The object may be used to suggest a list of options to the user. If we're making a site mainly for German audience then we probably want `49` to be the first. -Mas, ao correr o código, vemos uma imagem totalmente diferente: +But if we run the code, we see a totally different picture: -- EUA (1) vem em primeiro lugar, -- depois a Suiça (41), e assim por adiante. +- USA (1) goes first +- then Switzerland (41) and so on. -Os indicativos telefónicos, são ordenados por ordem ascendente, porque são inteiros. Por isso, vemos `1, 41, 44, 49`. +The phone codes go in the ascending sorted order, because they are integers. So we see `1, 41, 44, 49`. ````smart header="Integer properties? What's that?" -O termo "propriedade inteira" aqui, significa que uma *string* pode ser convertida para inteiro ('integer') e, de volta reconvertida sem qualquer alteração. +The "integer property" term here means a string that can be converted to-and-from an integer without a change. -Assim, "49" é um nome de propriedade inteiro porque, ao ser transformado num número inteiro e de volta reconvertido, continua o mesmo. Mas, "+49" e "1.2" não são: +So, "49" is an integer property name, because when it's transformed to an integer number and back, it's still the same. But "+49" and "1.2" are not: ```js run -// Math.trunc é uma função incorporada (*built-in function*) que remove a parte decimal - -alert( String(Math.trunc(Number("49"))) ); // "49", inalterado ⇒ propriedade inteira - -alert( String(Math.trunc(Number("+49"))) ); // "49", não o mesmo que "+49" ⇒ não é uma propriedade inteira - -alert( String(Math.trunc(Number("1.2"))) ); // "1", não o mesmo que "1.2" ⇒ não é uma propriedade inteira +// Math.trunc is a built-in function that removes the decimal part +alert( String(Math.trunc(Number("49"))) ); // "49", same, integer property +alert( String(Math.trunc(Number("+49"))) ); // "49", not same "+49" ⇒ not integer property +alert( String(Math.trunc(Number("1.2"))) ); // "1", not same "1.2" ⇒ not integer property ``` ```` -...Por outro lado, se as chaves (*keys*) forem não-inteiras, elas são listadas segundo a ordem em que foram criadas, por exemplo: +...On the other hand, if the keys are non-integer, then they are listed in the creation order, for instance: ```js run let user = { name: "John", surname: "Smith" }; -user.age = 25; // adicione mais uma propriedade +user.age = 25; // add one more *!* -// propriedades não-inteiras são listadas segundo a ordem em que foram criadas +// non-integer properties are listed in the creation order */!* for (let prop in user) { - alert( prop ); // 'name', 'surname', 'age' + alert( prop ); // name, surname, age } ``` -Portanto, para corrigir o problema dos indicativos telefónicos, podemos "aldrabar" tornando-os não-inteiros. Adicionar um sinal de mais `"+"`, antes de cada código é o suficiente. +So, to fix the issue with the phone codes, we can "cheat" by making the codes non-integer. Adding a plus `"+"` sign before each code is enough. -Desta forma: +Like this: ```js run let codes = { - "+49": "Alemanha", - "+41": "Suiça", - "+44": "Grã Bretanha", + "+49": "Germany", + "+41": "Switzerland", + "+44": "Great Britain", // .., - "+1": "EUA" + "+1": "USA" }; for (let code in codes) { @@ -457,30 +461,30 @@ for (let code in codes) { } ``` -Agora, funciona como pretendido. +Now it works as intended. -## Cópia por referência +## Copying by reference -Uma das principais diferenças entre objetos vs primitivos, está em que os primeiros são armazenados e copiados "por referência" (*by reference*). +One of the fundamental differences of objects vs primitives is that they are stored and copied "by reference". -Valores primitivos: *strings*, números, booleanos -- são atribuidos/copiados como "o próprio valor". +Primitive values: strings, numbers, booleans -- are assigned/copied "as a whole value". -Por exemplo: +For instance: ```js let message = "Hello!"; let phrase = message; ``` -Como resultado, temos duas variáveis independentes, mas cada uma armazenando a *string* (cadeia-de-carateres) `"Hello!"`. +As a result we have two independent variables, each one is storing the string `"Hello!"`. ![](variable-copy-value.svg) -Objetos não são assim. +Objects are not like that. -**Uma variável não armazena o próprio objeto, mas o seu "endereço em memória" (*address in memory*), por outras palavras "uma referência" (*reference*) a ele.** +**A variable stores not the object itself, but its "address in memory", in other words "a reference" to it.** -Aqui, está a imagem para o objeto: +Here's the picture for the object: ```js let user = { @@ -490,25 +494,25 @@ let user = { ![](variable-contains-reference.svg) -Aqui, o objeto é armazenado algures na memória. E a variável `user` contém uma "referência" para ele. +Here, the object is stored somewhere in memory. And the variable `user` has a "reference" to it. -**Quando uma variável com um objeto é copiada -- é a referência copiada, o objeto não é duplicado.** +**When an object variable is copied -- the reference is copied, the object is not duplicated.** -Se imaginarmos um objeto como um fichário, então uma variável será uma chave (*a key*) para ele. Copiando uma variável duplica a chave (*the key*), não o próprio fichário. +If we imagine an object as a cabinet, then a variable is a key to it. Copying a variable duplicates the key, but not the cabinet itself. -Por exemplo: +For instance: ```js no-beautify let user = { name: "John" }; -let admin = user; // copia a referência +let admin = user; // copy the reference ``` -Agora, temos duas variáveis, e cada uma com a referência para o mesmo objeto: +Now we have two variables, each one with the reference to the same object: ![](variable-copy-reference.svg) -Podemos utilizar qualquer das variáveis, para aceder ao fichário e alterar o seu conteúdo: +We can use any variable to access the cabinet and modify its contents: ```js run let user = { name: 'John' }; @@ -516,46 +520,46 @@ let user = { name: 'John' }; let admin = user; *!* -admin.name = 'Pete'; // alterado através da referência em "admin" +admin.name = 'Pete'; // changed by the "admin" reference */!* -alert(*!*user.name*/!*); // 'Pete', as alterações também são visíveis por meio da referência em "user" +alert(*!*user.name*/!*); // 'Pete', changes are seen from the "user" reference ``` -O exemplo acima, demonstra que apenas existe um objecto. Como se tivéssemos um fichário com duas chaves, e usássemos uma delas (`admin`) para o aceder. E depois, se mais tarde usássemos a outra chave (`user`) poderíamos ver as alterações. +The example above demonstrates that there is only one object. As if we had a cabinet with two keys and used one of them (`admin`) to get into it. Then, if we later use the other key (`user`) we would see changes. -### Comparação por referência +### Comparison by reference -Os operadores de igualdade `==` e de igualdade exata (*strict*) `===` para objetos funcionam exatamente da mesma forma. +The equality `==` and strict equality `===` operators for objects work exactly the same. -**Dois objetos apenas são iguais se eles forem o mesmo objeto.** +**Two objects are equal only if they are the same object.** -Por exemplo, duas variáveis referenciam o mesmo objeto, elas são iguais: +For instance, two variables reference the same object, they are equal: ```js run let a = {}; -let b = a; // cópia por referência +let b = a; // copy the reference -alert( a == b ); // true (verdadeiro), ambas as variáveis referenciam o mesmo objeto -alert( a === b ); // true (verdadeiro) +alert( a == b ); // true, both variables reference the same object +alert( a === b ); // true ``` -E aqui, dois objetos independentes não são iguais, muito embora ambos sejam vazios: +And here two independent objects are not equal, even though both are empty: ```js run let a = {}; -let b = {}; // dois objetos independentes +let b = {}; // two independent objects -alert( a == b ); // false (falso) +alert( a == b ); // false ``` -Para comparações como `obj1 > obj2` ou para uma comparação com um primitivo `obj == 5`, objetos são convertidos para primitivos. Estudaremos como funciona a conversão de objetos muito em breve, mas para dizer a verdade, tais comparações são muito raramente necessárias e são geralmente o resultado de um erro de código. +For comparisons like `obj1 > obj2` or for a comparison against a primitive `obj == 5`, objects are converted to primitives. We'll study how object conversions work very soon, but to tell the truth, such comparisons are necessary very rarely and usually are a result of a coding mistake. -### Objeto constante +### Const object -Um objeto declarado com `const` *pode* ser alterado. +An object declared as `const` *can* be changed. -Por exemplo: +For instance: ```js run const user = { @@ -569,9 +573,9 @@ user.age = 25; // (*) alert(user.age); // 25 ``` -Parece que a linha `(*)` irá causar um erro, mas não, não há totalmente qualquer problema. Isso, porque `const` apenas fixa o valor de `user`. Então, aqui `user` armazena uma referência para um mesmo objeto pelo tempo todo. A linha `(*)` vai para *dentro* do objeto, não faz uma re-atribuição a `user`. +It might seem that the line `(*)` would cause an error, but no, there's totally no problem. That's because `const` fixes the value of `user` itself. And here `user` stores the reference to the same object all the time. The line `(*)` goes *inside* the object, it doesn't reassign `user`. -A `const` produzirá um erro se tentarmos colocar em `user` qualquer outra coisa, por exemplo: +The `const` would give an error if we try to set `user` to something else, for instance: ```js run const user = { @@ -579,26 +583,26 @@ const user = { }; *!* -// Erro (não é possível reatribuir a 'user') +// Error (can't reassign user) */!* user = { name: "Pete" }; ``` -...Mas, se quisermos tornar as propriedades do objeto constantes? Então, aí `user.age = 25` produzirá um erro. Isso, também é possível. Iremos cobrir isto no capítulo . +...But what if we want to make constant object properties? So that `user.age = 25` would give an error. That's possible too. We'll cover it in the chapter . -## Clonar e fundir, Object.assign +## Cloning and merging, Object.assign -Portanto, a cópia de uma variável de objeto cria mais uma referência para o mesmo objeto. +So, copying an object variable creates one more reference to the same object. -Mas, se quisermos duplicar um objecto? Criar uma cópia independente, um *clone*? +But what if we need to duplicate an object? Create an independent copy, a clone? -Também se pode fazer, mas é um pouco mais difícil, porque não existe método incorporado (*built-in*) ao JavaScript para isso. Na verdade, isso raramente é necessário. A cópia por referência é a maior parte das vezes boa. +That's also doable, but a little bit more difficult, because there's no built-in method for that in JavaScript. Actually, that's rarely needed. Copying by reference is good most of the time. -Mas, se realmente quisermos isto, aí precisaremos de criar um novo objeto e replicar a estrutura do existente iterando pelas suas propriedades e copiando-as, digamos num nível primitivo. +But if we really want that, then we need to create a new object and replicate the structure of the existing one by iterating over its properties and copying them on the primitive level. -Desta forma: +Like this: ```js run let user = { @@ -607,32 +611,32 @@ let user = { }; *!* -let clone = {}; // o novo objeto vazio +let clone = {}; // the new empty object -// copiemos todas as propriedades de 'user' para aquele +// let's copy all user properties into it for (let key in user) { clone[key] = user[key]; } */!* -// agora,'clone' é um clone completamente independente -clone.name = "Pete"; // altere dados nele +// now clone is a fully independent clone +clone.name = "Pete"; // changed the data in it -alert( user.name ); // contudo, ainda está 'John' no objeto original +alert( user.name ); // still John in the original object ``` -Podemos também empregar o método [Object.assign](mdn:js/Object/assign) para isso. +Also we can use the method [Object.assign](mdn:js/Object/assign) for that. -A sintaxe é: +The syntax is: ```js Object.assign(dest, [src1, src2, src3...]) ``` -- Os argumentos `dest`, e `src1, ..., srcN` (que podem ser tantos quantos necessários) são objetos. -- Ele copia as propriedades de todos os objects `src1, ..., srcN` para `dest`. Por outras palavras, propriedades de todos os objetos, a começar pelo segundo, são copiadas para o primeiro. Depois, ele retorna `dest`. +- Arguments `dest`, and `src1, ..., srcN` (can be as many as needed) are objects. +- It copies the properties of all objects `src1, ..., srcN` into `dest`. In other words, properties of all arguments starting from the 2nd are copied into the 1st. Then it returns `dest`. -Por exemplo, podemos utilizá-lo para fundir vários objetos num só: +For instance, we can use it to merge several objects into one: ```js let user = { name: "John" }; @@ -640,25 +644,25 @@ let permissions1 = { canView: true }; let permissions2 = { canEdit: true }; *!* -// copia todas propriedades de 'permissions1' e 'permissions2' para 'user' +// copies all properties from permissions1 and permissions2 into user Object.assign(user, permissions1, permissions2); */!* -// agora, user = { name: "John", canView: true, canEdit: true } +// now user = { name: "John", canView: true, canEdit: true } ``` -Se, o objeto recetor (`user`) já tiver alguma propriedade com o mesmo nome, ela será substituída (*overwritten*): +If the receiving object (`user`) already has the same named property, it will be overwritten: ```js let user = { name: "John" }; -// substitua ('overwrite') 'nome', e adicione 'isAdmin' +// overwrite name, add isAdmin Object.assign(user, { name: "Pete", isAdmin: true }); -// agora, user = { name: "Pete", isAdmin: true } +// now user = { name: "Pete", isAdmin: true } ``` -Podemos também utilizar `Object.assign` para substituir o ciclo (*loop*) acima para uma clonagem simples: +We also can use `Object.assign` to replace the loop for simple cloning: ```js let user = { @@ -671,12 +675,11 @@ let clone = Object.assign({}, user); */!* ``` -Ele copia todas as propriedades de `user` para o objecto vazio e retorna este. Na verdade, é o mesmo laço (*loop*), mas mais curto. - -Até agora, assumimos que todas as propriedades de `user` são primitivas. Mas, propriedades podem ser referências para outros objetos. O que fazer nesse caso? +It copies all properties of `user` into the empty object and returns it. Actually, the same as the loop, but shorter. -Como aqui: +Until now we assumed that all properties of `user` are primitive. But properties can be references to other objects. What to do with them? +Like this: ```js run let user = { name: "John", @@ -689,10 +692,9 @@ let user = { alert( user.sizes.height ); // 182 ``` -Agora, não é suficiente efetuar a cópia `clone.sizes = user.sizes`, porque `user.sizes` é um objeto, e aí seria copiado por referência. Então, `clone` e `user` iriam partilhar a mesma propriedade "*sizes*": - -Deste modo: +Now it's not enough to copy `clone.sizes = user.sizes`, because the `user.sizes` is an object, it will be copied by reference. So `clone` and `user` will share the same sizes: +Like this: ```js run let user = { name: "John", @@ -704,48 +706,49 @@ let user = { let clone = Object.assign({}, user); -alert( user.sizes === clone.sizes ); // true (verdadeiro), é o mesmo objeto +alert( user.sizes === clone.sizes ); // true, same object -// 'user' e 'clone' partilham 'sizes' -user.sizes.width++; // altere uma propriedade num lugar -alert(clone.sizes.width); // 51, e verá o resultado a partir do outro +// user and clone share sizes +user.sizes.width++; // change a property from one place +alert(clone.sizes.width); // 51, see the result from the other one ``` -Para corrigir isso, deveriamos empregar o laço (*loop*) para clonagem, que examina cada valor de `user[key]` e, se for um objeto, então também replica essa estrutura. Essa, é chamada de uma "clonagem profunda" ("*deep cloning*"). +To fix that, we should use the cloning loop that examines each value of `user[key]` and, if it's an object, then replicate its structure as well. That is called a "deep cloning". + +There's a standard algorithm for deep cloning that handles the case above and more complex cases, called the [Structured cloning algorithm](http://w3c.github.io/html/infrastructure.html#safe-passing-of-structured-data). In order not to reinvent the wheel, we can use a working implementation of it from the JavaScript library [lodash](https://lodash.com), the method is called [_.cloneDeep(obj)](https://lodash.com/docs#cloneDeep). + -Existe um algoritmo padrão (*standard*) para clonagem profunda (deep cloning), que trata tanto do caso acima como de mais complexos, chamado de [Structured cloning algorithm](http://w3c.github.io/html/infrastructure.html#safe-passing-of-structured-data) (algoritmo de clonagem de estruturas). Para não se reinventar a roda, poderemos utilizar uma implementação operacional do mesmo disponível na biblioteca (*library*) de JavaScript [lodash](https://lodash.com), o método é chamado [_.cloneDeep(obj)](https://lodash.com/docs#cloneDeep). -## Sumário +## Summary -Objetos são *arrays* associativos (*associative arrays*), com várias funcionalidades especiais. +Objects are associative arrays with several special features. -Eles armazenam propriedades em pares chave-valor, onde: -- As chaves das propriedades devem ser *strings* ou símbolos (geralmente *strings*). -- Valores podem ser de qualquer tipo. +They store properties (key-value pairs), where: +- Property keys must be strings or symbols (usually strings). +- Values can be of any type. -Para aceder a uma propriedade, podemos utilizar: -- A notação por ponto: `obj.property`. -- A notação por parênteses retos `obj["property"]`. Os parênteses retos permitem receber a chave de uma variável, como por exemplo `obj[varWithKey]`. +To access a property, we can use: +- The dot notation: `obj.property`. +- Square brackets notation `obj["property"]`. Square brackets allow to take the key from a variable, like `obj[varWithKey]`. -Operadores adicionais: -- Para remover uma propriedade: `delete obj.prop`. -- Para verificar se uma propriedade com uma dada chave existe: `"key" in obj`. -- Para iterar sobre um objeto: o ciclo `for (let key in obj)`. +Additional operators: +- To delete a property: `delete obj.prop`. +- To check if a property with the given key exists: `"key" in obj`. +- To iterate over an object: `for (let key in obj)` loop. -Objetos são atribuidos e copiados por referência. Por outras palavras, uma variável não armazena o "valor do objeto", mas uma "referência" (endereço em memória) do valor. Assim, copiar tal variável ou passá-la como argumento de uma função copia tal referência, não o objeto. Todas as operações sobre cópias de referências (como adicionar/remover propriedades) são executadas sobre um mesmo único objeto. +Objects are assigned and copied by reference. In other words, a variable stores not the "object value", but a "reference" (address in memory) for the value. So copying such a variable or passing it as a function argument copies that reference, not the object. All operations via copied references (like adding/removing properties) are performed on the same single object. - Para efetuar uma "verdadeira cópia" (um clone), podemos utilizar `Object.assign` ou [_.cloneDeep(obj)](https://lodash.com/docs#cloneDeep). +To make a "real copy" (a clone) we can use `Object.assign` or [_.cloneDeep(obj)](https://lodash.com/docs#cloneDeep). -O que estudámos neste capítulo é o chamado "objeto simples" ("*plain object*"), ou simplesmente `Objeto`. +What we've studied in this chapter is called a "plain object", or just `Object`. -Existem muitos outros tipos de objetos em JavaScript: +There are many other kinds of objects in JavaScript: -- `Array` para armazenar coleções de dados ordenadas, -- `Date` para armazenar informação sobre data e tempo, -- `Error` para armazenar informação sobre um erro. -- ...E outros mais. +- `Array` to store ordered data collections, +- `Date` to store the information about the date and time, +- `Error` to store the information about an error. +- ...And so on. -Eles têm as suas funcionalidades especiais, que estudaremos mais adiante. Por vezes, pessoas dizem algo como "o tipo -Array" ou "o tipo Data" (*Date*), mas formalmente eles não são própriamente tipos, mas pertencem a um único tipo de dados "objeto". E o extendem de várias formas. +They have their special features that we'll study later. Sometimes people say something like "Array type" or "Date type", but formally they are not types of their own, but belong to a single "object" data type. And they extend it in various ways. -Objetos em JavaScript são muito poderosos. Aqui, apenas tocámos na superfície de um realmente amplo tópico. Iremos, mais especificamente, trabalhar e aprender sobre objetos em futuras partes do tutorial. +Objects in JavaScript are very powerful. Here we've just scratched the surface of a topic that is really huge. We'll be closely working with objects and learning more about them in further parts of the tutorial. diff --git a/1-js/04-object-basics/index.md b/1-js/04-object-basics/index.md index 991117d25..d2387aafa 100644 --- a/1-js/04-object-basics/index.md +++ b/1-js/04-object-basics/index.md @@ -1 +1 @@ -# Objetos: o básico +# Objects: the basics From 025fe80e3bff8ea3e4e638cbcea5fcf30e6449db Mon Sep 17 00:00:00 2001 From: odsantos Date: Thu, 7 Nov 2019 23:12:32 +0100 Subject: [PATCH 3/3] add translate to object-methods directory files --- .../2-check-syntax/solution.md | 26 +-- .../04-object-methods/2-check-syntax/task.md | 8 +- .../04-object-methods/3-why-this/solution.md | 21 +- .../04-object-methods/3-why-this/task.md | 9 +- .../4-object-property-this/solution.md | 19 +- .../4-object-property-this/task.md | 11 +- .../7-calculator/_js.view/test.js | 6 +- .../7-calculator/solution.md | 2 +- .../04-object-methods/7-calculator/task.md | 15 +- .../8-chain-calls/_js.view/test.js | 10 +- .../8-chain-calls/solution.md | 6 +- .../04-object-methods/8-chain-calls/task.md | 14 +- .../04-object-methods/article.md | 215 +++++++++--------- 13 files changed, 177 insertions(+), 185 deletions(-) diff --git a/1-js/04-object-basics/04-object-methods/2-check-syntax/solution.md b/1-js/04-object-basics/04-object-methods/2-check-syntax/solution.md index e2e87de7c..3554a5be4 100644 --- a/1-js/04-object-basics/04-object-methods/2-check-syntax/solution.md +++ b/1-js/04-object-basics/04-object-methods/2-check-syntax/solution.md @@ -1,6 +1,6 @@ -**Error**! +**Erro**! -Try it: +Tente isto: ```js run let user = { @@ -8,22 +8,22 @@ let user = { go: function() { alert(this.name) } } -(user.go)() // error! +(user.go)() // erro! ``` -The error message in most browsers does not give understanding what went wrong. +A mensagem de erro, na maior parte dos navegadores (*browsers*), não nos dá uma compreensão do que ocorre de errado. -**The error appears because a semicolon is missing after `user = {...}`.** +**O erro aparece porque falta um ponto-e-vírgula depois de `user = {...}`.** -JavaScript does not assume a semicolon before a bracket `(user.go)()`, so it reads the code like: +JavaScript não assume um ponto-e-vírgula antes do parêntese de `(user.go)()`, por isso lê o código como: ```js no-beautify let user = { go:... }(user.go)() ``` -Then we can also see that such a joint expression is syntactically a call of the object `{ go: ... }` as a function with the argument `(user.go)`. And that also happens on the same line with `let user`, so the `user` object has not yet even been defined, hence the error. +Assim, podemos também observar que, tal expressão conjunta é sintáticamente uma chamada do objeto `{ go: ... }` como uma função, tomando `(user.go)` como argumento. E, isso também ocorre na mesma linha que `let user`, então o objeto `user` ainda não foi definido, e por isto o erro. -If we insert the semicolon, all is fine: +Se inserirmos o ponto-e-vírgula, tudo estará bem: ```js run let user = { @@ -31,13 +31,7 @@ let user = { go: function() { alert(this.name) } }*!*;*/!* -(user.go)() // John +(user.go)() // 'John' ``` -Please note that brackets around `(user.go)` do nothing here. Usually they setup the order of operations, but here the dot `.` works first anyway, so there's no effect. Only the semicolon thing matters. - - - - - - +Por favor, note que os parênteses em `(user.go)` nada aqui fazem. Geralmente, eles estabelecem a ordem das operações, mas aqui o ponto `.` já funciona à partida, então não têm efeito algum. Apenas, aquele ponto-e-vírgula importa. diff --git a/1-js/04-object-basics/04-object-methods/2-check-syntax/task.md b/1-js/04-object-basics/04-object-methods/2-check-syntax/task.md index f40d68735..ef43de48c 100644 --- a/1-js/04-object-basics/04-object-methods/2-check-syntax/task.md +++ b/1-js/04-object-basics/04-object-methods/2-check-syntax/task.md @@ -1,10 +1,10 @@ -importance: 2 +importância: 2 --- -# Syntax check +# Verificação sintática -What is the result of this code? +Qual o resultado deste código? ```js no-beautify @@ -16,4 +16,4 @@ let user = { (user.go)() ``` -P.S. There's a pitfall :) +P.S. Existe um falha :) diff --git a/1-js/04-object-basics/04-object-methods/3-why-this/solution.md b/1-js/04-object-basics/04-object-methods/3-why-this/solution.md index 89bc0d722..c48fcdceb 100644 --- a/1-js/04-object-basics/04-object-methods/3-why-this/solution.md +++ b/1-js/04-object-basics/04-object-methods/3-why-this/solution.md @@ -1,22 +1,21 @@ -Here's the explanations. +Aqui estão as explicações. -1. That's a regular object method call. +1. É uma regular invocação do método do objeto. -2. The same, brackets do not change the order of operations here, the dot is first anyway. +2. O mesmo. Aqui, os parênteses não alteram a ordem das operações, o ponto já funciona à primeira. -3. Here we have a more complex call `(expression).method()`. The call works as if it were split into two lines: +3. Aqui, temos uma chamada `(expression).method()` mais complexa. A chamada funciona como se fosse particionada em duas linhas: ```js no-beautify - f = obj.go; // calculate the expression - f(); // call what we have + f = obj.go; // calcula a expressão + f(); // invoca o resultado ``` - Here `f()` is executed as a function, without `this`. + Aqui, `f()` é executada como uma função, sem `this`. -4. The similar thing as `(3)`, to the left of the dot `.` we have an expression. +4. Algo similar a `(3)`, à esquerda do ponto `.` temos uma expressão. -To explain the behavior of `(3)` and `(4)` we need to recall that property accessors (dot or square brackets) return a value of the Reference Type. - -Any operation on it except a method call (like assignment `=` or `||`) turns it into an ordinary value, which does not carry the information allowing to set `this`. +Para explicar o comportamento de `(3)` e `(4)`, recordemo-nos que propriedades acessoras (o ponto ou os parênteses retos) retornam um valor do Tipo *Reference*. +Qualquer operação com elas (como, atribuição `=` ou `||`), exceto a chamada a um método, o transforma num valor ordinário, o qual não transporta a informação necessária para configurar `this`. diff --git a/1-js/04-object-basics/04-object-methods/3-why-this/task.md b/1-js/04-object-basics/04-object-methods/3-why-this/task.md index f22de29cc..919f17220 100644 --- a/1-js/04-object-basics/04-object-methods/3-why-this/task.md +++ b/1-js/04-object-basics/04-object-methods/3-why-this/task.md @@ -1,12 +1,12 @@ -importance: 3 +importância: 3 --- -# Explain the value of "this" +# Explique o valor de "this" -In the code below we intend to call `user.go()` method 4 times in a row. +No código abaixo, pretendemos invocar o método `user.go()` 4 vezes seguidas. -But calls `(1)` and `(2)` works differently from `(3)` and `(4)`. Why? +Mas, as chamadas `(1)` e `(2)` funcionam de forma diferente do que as `(3)` e `(4)`. Porquê? ```js run no-beautify let obj, method; @@ -23,4 +23,3 @@ obj.go(); // (1) [object Object] (obj.go || obj.stop)(); // (4) undefined ``` - diff --git a/1-js/04-object-basics/04-object-methods/4-object-property-this/solution.md b/1-js/04-object-basics/04-object-methods/4-object-property-this/solution.md index f5773ec2c..14f42f296 100644 --- a/1-js/04-object-basics/04-object-methods/4-object-property-this/solution.md +++ b/1-js/04-object-basics/04-object-methods/4-object-property-this/solution.md @@ -1,6 +1,6 @@ -**Answer: an error.** +**Resposta: um erro.** -Try it: +Tente isto: ```js run function makeUser() { return { @@ -12,17 +12,18 @@ function makeUser() { let user = makeUser(); alert( user.ref.name ); // Error: Cannot read property 'name' of undefined + // (Erro: não é possível ler a propriedade 'name' de undefined) ``` -That's because rules that set `this` do not look at object literals. +Isto, porque regras que estabelecem `this` não têm em conta objetos literais. -Here the value of `this` inside `makeUser()` is `undefined`, because it is called as a function, not as a method. +Aqui, o valor de `this` dentro de `makeUser()` está `undefined`, porque é invocado como uma função, não como um método. -And the object literal itself has no effect on `this`. The value of `this` is one for the whole function, code blocks and object literals do not affect it. +E um objeto literal não possui qualquer efeito sobre `this`. O valor de `this` é o mesmo para toda uma função, e tanto blocos de código como objetos literais não exercem qualquer influência sobre ele. -So `ref: this` actually takes current `this` of the function. +Assim, na realidade `ref: this` recebe o valor atual `this` da função. -Here's the opposite case: +Aqui, o caso oposto: ```js run function makeUser() { @@ -38,9 +39,9 @@ function makeUser() { let user = makeUser(); -alert( user.ref().name ); // John +alert( user.ref().name ); // 'John' ``` -Now it works, because `user.ref()` is a method. And the value of `this` is set to the object before dot `.`. +Agora funciona, porque `user.ref()` é um método. E, o valor de `this` já é uma referência ao objeto antes do ponto `.`. diff --git a/1-js/04-object-basics/04-object-methods/4-object-property-this/task.md b/1-js/04-object-basics/04-object-methods/4-object-property-this/task.md index 4784b082c..200392df1 100644 --- a/1-js/04-object-basics/04-object-methods/4-object-property-this/task.md +++ b/1-js/04-object-basics/04-object-methods/4-object-property-this/task.md @@ -1,12 +1,12 @@ -importance: 5 +importância: 5 --- -# Using "this" in object literal +# Usando "this" num objeto literal -Here the function `makeUser` returns an object. +Aqui, a função `makeUser` retorna um objeto. -What is the result of accessing its `ref`? Why? +Qual o resultado de aceder à sua `ref`? Porquê? ```js function makeUser() { @@ -18,6 +18,5 @@ function makeUser() { let user = makeUser(); -alert( user.ref.name ); // What's the result? +alert( user.ref.name ); // Qual o resultado? ``` - diff --git a/1-js/04-object-basics/04-object-methods/7-calculator/_js.view/test.js b/1-js/04-object-basics/04-object-methods/7-calculator/_js.view/test.js index 1f71eda4c..1c47c6a1e 100644 --- a/1-js/04-object-basics/04-object-methods/7-calculator/_js.view/test.js +++ b/1-js/04-object-basics/04-object-methods/7-calculator/_js.view/test.js @@ -2,7 +2,7 @@ describe("calculator", function() { - context("when 2 and 3 entered", function() { + context("quando são entrados 2 e 3", function() { beforeEach(function() { sinon.stub(window, "prompt"); @@ -16,11 +16,11 @@ describe("calculator", function() { prompt.restore(); }); - it("the sum is 5", function() { + it("a soma é 5", function() { assert.equal(calculator.sum(), 5); }); - it("the multiplication product is 6", function() { + it("o produto da multiplicação é 6", function() { assert.equal(calculator.mul(), 6); }); }); diff --git a/1-js/04-object-basics/04-object-methods/7-calculator/solution.md b/1-js/04-object-basics/04-object-methods/7-calculator/solution.md index 459997624..b604c3c9c 100644 --- a/1-js/04-object-basics/04-object-methods/7-calculator/solution.md +++ b/1-js/04-object-basics/04-object-methods/7-calculator/solution.md @@ -1,5 +1,5 @@ -```js run demo solution +```js execute a solução demo let calculator = { sum() { return this.a + this.b; diff --git a/1-js/04-object-basics/04-object-methods/7-calculator/task.md b/1-js/04-object-basics/04-object-methods/7-calculator/task.md index aa22608ec..acce94c85 100644 --- a/1-js/04-object-basics/04-object-methods/7-calculator/task.md +++ b/1-js/04-object-basics/04-object-methods/7-calculator/task.md @@ -1,18 +1,18 @@ -importance: 5 +importância: 5 --- -# Create a calculator +# Crie uma calculadora -Create an object `calculator` with three methods: +Crie um objeto `calculator` com três métodos: -- `read()` prompts for two values and saves them as object properties. -- `sum()` returns the sum of saved values. -- `mul()` multiplies saved values and returns the result. +- `read()` pergunta (*prompts*) por dois valores e os guarda (*saves*) como propriedades de um objeto. +- `sum()` retorna a soma dos valores guardados. +- `mul()` multiplica os valores guardados e retorna o resultado. ```js let calculator = { - // ... your code ... + // ... o seu código ... }; calculator.read(); @@ -21,4 +21,3 @@ alert( calculator.mul() ); ``` [demo] - diff --git a/1-js/04-object-basics/04-object-methods/8-chain-calls/_js.view/test.js b/1-js/04-object-basics/04-object-methods/8-chain-calls/_js.view/test.js index a2b17fcc4..e9cb1f8de 100644 --- a/1-js/04-object-basics/04-object-methods/8-chain-calls/_js.view/test.js +++ b/1-js/04-object-basics/04-object-methods/8-chain-calls/_js.view/test.js @@ -8,24 +8,24 @@ describe('Ladder', function() { ladder.step = 0; }); - it('up() should return this', function() { + it('up() deveria retornar this', function() { assert.equal(ladder.up(), ladder); }); - it('down() should return this', function() { + it('down() deveria retornar this', function() { assert.equal(ladder.down(), ladder); }); - it('showStep() should call alert', function() { + it('showStep() deveria chamar alert', function() { ladder.showStep(); assert(alert.called); }); - it('up() should increase step', function() { + it('up() deveria incrementar step', function() { assert.equal(ladder.up().up().step, 2); }); - it('down() should decrease step', function() { + it('down() deveria decrementar step', function() { assert.equal(ladder.down().step, -1); }); diff --git a/1-js/04-object-basics/04-object-methods/8-chain-calls/solution.md b/1-js/04-object-basics/04-object-methods/8-chain-calls/solution.md index 2b47873fc..620384a37 100644 --- a/1-js/04-object-basics/04-object-methods/8-chain-calls/solution.md +++ b/1-js/04-object-basics/04-object-methods/8-chain-calls/solution.md @@ -1,6 +1,6 @@ -The solution is to return the object itself from every call. +A solução será retornar o próprio objeto em cada chamada. -```js run demo +```js execute demo let ladder = { step: 0, up() { @@ -26,7 +26,7 @@ let ladder = { ladder.up().up().down().up().down().showStep(); // 1 ``` -We also can write a single call per line. For long chains it's more readable: +Podemos também escrever uma única chamada por linha. Para longas cadeias é mais legível: ```js ladder diff --git a/1-js/04-object-basics/04-object-methods/8-chain-calls/task.md b/1-js/04-object-basics/04-object-methods/8-chain-calls/task.md index eca9f4e92..8c38cbe9c 100644 --- a/1-js/04-object-basics/04-object-methods/8-chain-calls/task.md +++ b/1-js/04-object-basics/04-object-methods/8-chain-calls/task.md @@ -1,10 +1,10 @@ -importance: 2 +importância: 2 --- -# Chaining +# Encadeamento -There's a `ladder` object that allows to go up and down: +Existe um objeto `ladder` (escada) que permite subir e descer: ```js let ladder = { @@ -15,13 +15,13 @@ let ladder = { down() { this.step--; }, - showStep: function() { // shows the current step + showStep: function() { // mostra o atual degrau alert( this.step ); } }; ``` -Now, if we need to make several calls in sequence, can do it like this: +Agora, se precisarmos de fazer várias chamadas em sequência, podemos fazê-las desta forma: ```js ladder.up(); @@ -30,10 +30,10 @@ ladder.down(); ladder.showStep(); // 1 ``` -Modify the code of `up`, `down` and `showStep` to make the calls chainable, like this: +Modifique o código de `up`, `down` e `showStep` para tornar as chamadas encadeáveis, como: ```js ladder.up().up().down().showStep(); // 1 ``` -Such approach is widely used across JavaScript libraries. +Tal abordagem é amplamente utilizada em bibliotecas (*libraries*) de JavaScript. diff --git a/1-js/04-object-basics/04-object-methods/article.md b/1-js/04-object-basics/04-object-methods/article.md index 0418adee0..3e6f5ef45 100644 --- a/1-js/04-object-basics/04-object-methods/article.md +++ b/1-js/04-object-basics/04-object-methods/article.md @@ -1,6 +1,6 @@ -# Object methods, "this" +# Métodos do objeto, "this" -Objects are usually created to represent entities of the real world, like users, orders and so on: +Objectos, geralmente são criados como representação de entidades no mundo real, como utilizadores, encomendas e assim por diante: ```js let user = { @@ -9,13 +9,13 @@ let user = { }; ``` -And, in the real world, a user can *act*: select something from the shopping cart, login, logout etc. +E, no mundo real, um utilizador pode *interagir*: selecionar algo de um carrinho de compras, *login*, *logout*, etc. -Actions are represented in JavaScript by functions in properties. +As interações, são representadas em JavaScript por funções em propriedades. -## Method examples +## Exemplos de métodos -For the start, let's teach the `user` to say hello: +Para começar, ensinemos ao `user` a dizer olá: ```js run let user = { @@ -25,22 +25,22 @@ let user = { *!* user.sayHi = function() { - alert("Hello!"); + alert("Olá!"); }; */!* -user.sayHi(); // Hello! +user.sayHi(); // Olá! ``` -Here we've just used a Function Expression to create the function and assign it to the property `user.sayHi` of the object. +Aqui, acabamos de empregar uma Expressão de Função (*Function Expression*) para criar uma função e a atribuir à propriedade do objeto `user.sayHi`. -Then we can call it. The user can now speak! +Depois, a podemos invocar. O utilizador pode agora falar! -A function that is the property of an object is called its *method*. +Uma função que seja uma propriedade de um objeto, é chamada de seu *método* (*method*). -So, here we've got a method `sayHi` of the object `user`. +Assim, temos o método `sayHi` do objeto `user`. -Of course, we could use a pre-declared function as a method, like this: +Evidentemente, poderiamos usar uma função pré-declarada como método. Desta forma: ```js run let user = { @@ -48,61 +48,61 @@ let user = { }; *!* -// first, declare +// primeiro, declare function sayHi() { alert("Hello!"); }; -// then add as a method +// Depois adicine como método user.sayHi = sayHi; */!* user.sayHi(); // Hello! ``` -```smart header="Object-oriented programming" -When we write our code using objects to represent entities, that's called an [object-oriented programming](https://en.wikipedia.org/wiki/Object-oriented_programming), in short: "OOP". +```smart header="Programação orientada por objetos" +Quando escrevemos o nosso código empregando objetos para representar entidades, é chamada de [Programação orientada a objetos](https://pt.wikipedia.org/wiki/Programa%C3%A7%C3%A3o_orientada_a_objetos) (*object-oriented programming*), abreviadamente: "OOP". -OOP is a big thing, an interesting science of its own. How to choose the right entities? How to organize the interaction between them? That's architecture, and there are great books on that topic, like "Design Patterns: Elements of Reusable Object-Oriented Software" by E.Gamma, R.Helm, R.Johnson, J.Vissides or "Object-Oriented Analysis and Design with Applications" by G.Booch, and more. +OOP (Programação orientada por objetos) é algo grande, uma ciência interessante por si mesma. Como escolher as entidades certas? Como organizar a interação enter elas? É arquitetura, e existem grandes livros neste tópico, como "Design Patterns: Elements of Reusable Object-Oriented Software" by E.Gamma, R.Helm, R.Johnson, J.Vissides ou "Object-Oriented Analysis and Design with Applications" by G.Booch, e mais. ``` -### Method shorthand +### Abreviação de método -There exists a shorter syntax for methods in an object literal: +Existe uma sintaxe mais curta para métodos num objeto literal: ```js -// these objects do the same +// estes objetos fazem o mesmo let user = { sayHi: function() { - alert("Hello"); + alert("Olá"); } }; -// method shorthand looks better, right? +// a abreviação de método tem melhor aspeto, não tem? let user = { *!* - sayHi() { // same as "sayHi: function()" + sayHi() { // o mesmo que "sayHi: function()" */!* - alert("Hello"); + alert("Olá"); } }; ``` -As demonstrated, we can omit `"function"` and just write `sayHi()`. +Como demonstrado, podemos omitir `"function"` e apenas escrever `sayHi()`. -To tell the truth, the notations are not fully identical. There are subtle differences related to object inheritance (to be covered later), but for now they do not matter. In almost all cases the shorter syntax is preferred. +Na verdade, as notações não são completamente idênticas. Existem diferenças subtis em relação à herança do objeto (a ser estudado mais adiante), mas por ora elas não interessam. Em quase todos os casos, a sintaxe mais curta é preferível. -## "this" in methods +## "*this*" em métodos -It's common that an object method needs to access the information stored in the object to do its job. +É comum que um método de um objeto precise de aceder à informação armazenada no objeto para executar a sua tarefa. -For instance, the code inside `user.sayHi()` may need the name of the `user`. +Por exemplo, o código dentro de `user.sayHi()` pode precisar do nome do `user`. -**To access the object, a method can use the `this` keyword.** +**Para aceder ao objeto, um método pode usar a palavra-chave `this`.** -The value of `this` is the object "before dot", the one used to call the method. +O valor de `this` é o objeto "antes do ponto", o utilizado para chamar o método. -For instance: +Por exemplo: ```js run let user = { @@ -120,9 +120,9 @@ let user = { user.sayHi(); // John ``` -Here during the execution of `user.sayHi()`, the value of `this` will be `user`. +Aqui, durante a execução de `user.sayHi()`, o valor de `this` será `user`. -Technically, it's also possible to access the object without `this`, by referencing it via the outer variable: +Tecnicamente, também é possível aceder ao objeto sem `this`, por meio de uma referência numa variável externa: ```js let user = { @@ -131,16 +131,16 @@ let user = { sayHi() { *!* - alert(user.name); // "user" instead of "this" + alert(user.name); // "user" em vez de "this" */!* } }; ``` -...But such code is unreliable. If we decide to copy `user` to another variable, e.g. `admin = user` and overwrite `user` with something else, then it will access the wrong object. +...Mas tal código não é fiável. Se decidirmos copiar `user` para outra variável, por exemplo `admin = user` e colocar outro valor em `user`, então a cópia irá aceder ao valor errado. -That's demonstrated below: +Isso, é demonstrado abaixo: ```js run let user = { @@ -149,7 +149,7 @@ let user = { sayHi() { *!* - alert( user.name ); // leads to an error + alert( user.name ); // leva a um erro */!* } @@ -157,18 +157,18 @@ let user = { let admin = user; -user = null; // overwrite to make things obvious +user = null; // atribui outro valor, para ser óbvio -admin.sayHi(); // Whoops! inside sayHi(), the old name is used! error! +admin.sayHi(); // Whoops! dentro de sayHi(), o nome antigo é utilizado! erro! ``` -If we used `this.name` instead of `user.name` inside the `alert`, then the code would work. +Se empregássemos `this.name` em vez de `user.name` dentro de `alert`, então o código funcionaria. -## "this" is not bound +## "*this*" não está vinculado -In JavaScript, "this" keyword behaves unlike most other programming languages. First, it can be used in any function. +Em JavaScript, a palavra-chave "this" não se comporta como em muitas outras linguagens de programação. Em primeiro lugar, pode ser utilizada em qualquer função. -There's no syntax error in the code like that: +Não existe algum erro de sintaxe num código como este: ```js function sayHi() { @@ -176,9 +176,9 @@ function sayHi() { } ``` -The value of `this` is evaluated during the run-time. And it can be anything. +O valor de `this` é avaliado em tempo de execução. E, pode ser qualquer coisa. -For instance, the same function may have different "this" when called from different objects: +Por exemplo, uma mesma função pode ter diferentes "*this*" quando invocada de diferentes objetos: ```js run let user = { name: "John" }; @@ -189,20 +189,20 @@ function sayHi() { } *!* -// use the same functions in two objects +// use a mesma função em dois objectos user.f = sayHi; admin.f = sayHi; */!* -// these calls have different this -// "this" inside the function is the object "before the dot" +// estas chamadas têm diferentes 'this' +// "this" dentro da função é o objeto "antes do ponto" user.f(); // John (this == user) admin.f(); // Admin (this == admin) -admin['f'](); // Admin (dot or square brackets access the method – doesn't matter) +admin['f'](); // Admin (ponto ou parênteses retos para aceder ao método – é irrelevante) ``` -Actually, we can call the function without an object at all: +Na verdade, podemos invocar a função sem nenhum objeto: ```js run function sayHi() { @@ -212,31 +212,31 @@ function sayHi() { sayHi(); // undefined ``` -In this case `this` is `undefined` in strict mode. If we try to access `this.name`, there will be an error. +Neste caso, `this` está `undefined` no modo estrito (*strict mode*). Se tentarmos aceder a `this.name`, haverá um erro. -In non-strict mode the value of `this` in such case will be the *global object* (`window` in a browser, we'll get to it later in the chapter [](info:global-object)). This is a historical behavior that `"use strict"` fixes. +No modo não-estrito (*non-strict mode*), `this` será o *objeto global* (`window` num *browser*, o que veremos mais adiante no capítulo [Global object](info:global-object). Este, é um procedimento histórico que `"use strict"` corrige. -Please note that usually a call of a function that uses `this` without an object is not normal, but rather a programming mistake. If a function has `this`, then it is usually meant to be called in the context of an object. +Por favor, note que geralmente uma chamada de função que use `this` sem um objeto não é normal, mas sim um erro de programação. Se uma função contiver `this`, então deverá ser invocada no contexto de um objeto. -```smart header="The consequences of unbound `this`" -If you come from another programming language, then you are probably used to the idea of a "bound `this`", where methods defined in an object always have `this` referencing that object. +```smart header="As consequências de 'this' não vinculado" +Se vem de uma outra linguagem de programação, então provavelmente está habituado à ideia de um `this` "vinculado", onde métodos definidos num objeto têm sempre `this` como referência a esse objeto. -In JavaScript `this` is "free", its value is evaluated at call-time and does not depend on where the method was declared, but rather on what's the object "before the dot". +Em JavaScript `this` é "livre", o seu valor é avaliado no momento da invocação (*call-time*) e não depende de onde o método foi declarado, mas sim de qual o objeto "antes do ponto". -The concept of run-time evaluated `this` has both pluses and minuses. On the one hand, a function can be reused for different objects. On the other hand, greater flexibility opens a place for mistakes. +O conceito de `this` avaliado em tempo-de-execução (*run-time*), possui ambas vantagens e desvantagens. Por um lado, uma função pode ser re-utilizada em objetos diferentes. Por outro, uma maior flexibilidade abre espaço para erros. -Here our position is not to judge whether this language design decision is good or bad. We'll understand how to work with it, how to get benefits and evade problems. +Aqui, a nossa posição não é julgar se a decisão no desenho desta linguagem é boa ou má. Iremos compreender como trabalhar com ele, como colher benefícios e como evitar problemas. ``` -## Internals: Reference Type +## Internamente: o Tipo Referência -```warn header="In-depth language feature" -This section covers an advanced topic, to understand certain edge-cases better. +```warn header="Intrínsica funcionalidade da linguagem" +Esta secção cobre um tópico avançado, para uma melhor compreensão de certos casos-limite. -If you want to go on faster, it can be skipped or postponed. +Se quiser avançar mais rapidamente, pode ser saltada ou adiada. ``` -An intricate method call can lose `this`, for instance: +Um método complicado pode perder `this`, por exemplo: ```js run let user = { @@ -245,40 +245,40 @@ let user = { bye() { alert("Bye"); } }; -user.hi(); // John (the simple call works) +user.hi(); // John (a chamada simples funciona) *!* -// now let's call user.hi or user.bye depending on the name -(user.name == "John" ? user.hi : user.bye)(); // Error! +// agora vamos invocar user.hi ou user.bye, dependendo do nome +(user.name == "John" ? user.hi : user.bye)(); // Erro! */!* ``` -On the last line there is a ternary operator that chooses either `user.hi` or `user.bye`. In this case the result is `user.hi`. +Na última linha, existe um operador ternário (*ternary operator*) que permite escolher `user.hi` ou `user.bye`. Para o presente caso, o resultado será `user.hi`. -The method is immediately called with parentheses `()`. But it doesn't work right! +O método é imediatamente chamado com os parênteses `()`. Mas, não funciona corretamente! -You can see that the call results in an error, because the value of `"this"` inside the call becomes `undefined`. +Pode observar que a chamada resulta num erro, porque o valor de `"this"` dentro da chamada torna-se `undefined`. -This works (object dot method): +Isto funciona (objeto ponto método): ```js user.hi(); ``` -This doesn't (evaluated method): +Isto não (método avaliado): ```js -(user.name == "John" ? user.hi : user.bye)(); // Error! +(user.name == "John" ? user.hi : user.bye)(); // Erro! ``` -Why? If we want to understand why it happens, let's get under the hood of how `obj.method()` call works. +Porquê? Se, quisermos compreender porque acontece, vamos analisar como a chamada `obj.method()` funciona. -Looking closely, we may notice two operations in `obj.method()` statement: +Observando mais de perto, podemos notar duas operações na instrução `obj.method()`: -1. First, the dot `'.'` retrieves the property `obj.method`. -2. Then parentheses `()` execute it. +1. Primeiro, o ponto `'.'` obtem a propriedade `obj.method`. +2. Depois, os parênteses `()` a executam. -So, how does the information about `this` get passed from the first part to the second one? +Assim, como a informação sobre `this` passa da primeira parte para segunda? -If we put these operations on separate lines, then `this` will be lost for sure: +Se colocarmos essas operações em linhas separadas, então `this` de certeza será perdido: ```js run let user = { @@ -287,42 +287,42 @@ let user = { } *!* -// split getting and calling the method in two lines +// particione o obter e chamar o método em duas linhas let hi = user.hi; -hi(); // Error, because this is undefined +hi(); // Erro, porque 'this' está undefined */!* ``` -Here `hi = user.hi` puts the function into the variable, and then on the last line it is completely standalone, and so there's no `this`. +Aqui, `hi = user.hi` coloca a função numa variável, e a seguir na última linha ela está completamente isolada, não existe nenhum `this`. -**To make `user.hi()` calls work, JavaScript uses a trick -- the dot `'.'` returns not a function, but a value of the special [Reference Type](https://tc39.github.io/ecma262/#sec-reference-specification-type).** +**Para fazer a chamada `user.hi()` funcionar, JavaScript usa um truque -- o ponto `'.'` não retorna um função , mas um valor especial [Reference Type](https://tc39.github.io/ecma262/#sec-reference-specification-type) (do tipo referência).** -The Reference Type is a "specification type". We can't explicitly use it, but it is used internally by the language. +O *Reference Type* é um "tipo incorporado na especificação". Não o podemos utilizar explicitamente, mas é usado internamente pela linguagem. -The value of Reference Type is a three-value combination `(base, name, strict)`, where: +O valor do *Reference Type* é uma combinação de três-valores `(base, name, strict)`, onde: -- `base` is the object. -- `name` is the property. -- `strict` is true if `use strict` is in effect. +- `base` é o objeto. +- `name` é a propriedade. +- `strict` é *true* (verdadeiro) se `use strict` estiver em efeito. -The result of a property access `user.hi` is not a function, but a value of Reference Type. For `user.hi` in strict mode it is: +O resultado de um acesso à propriedade `user.hi` não é uma função, mas um valor do tipo Referência (*Reference Type*). Para `user.hi` em modo estrito (*strict mode*) ele é: ```js -// Reference Type value +// valor do Tipo Referência (user, "hi", true) ``` -When parentheses `()` are called on the Reference Type, they receive the full information about the object and its method, and can set the right `this` (`=user` in this case). +Quando parênteses `()` são chamados sobre o *Reference Type*, eles recebem uma completa informação sobre o objeto e o seu método, e pode ser estabelecido o `this` certo (`=user`, neste caso). -Any other operation like assignment `hi = user.hi` discards the reference type as a whole, takes the value of `user.hi` (a function) and passes it on. So any further operation "loses" `this`. +Qualquer outra operação, como a atribuição `hi = user.hi` descarta totalmente o tipo referência, toma o valor de `user.hi` (uma função) e o passa. Assim, qualquer operação posterior "perde" o `this`. -So, as the result, the value of `this` is only passed the right way if the function is called directly using a dot `obj.method()` or square brackets `obj['method']()` syntax (they do the same here). Later in this tutorial, we will learn various ways to solve this problem such as [func.bind()](/bind#solution-2-bind). +Deste modo, como resultado, o valor de `this` apenas é passado da forma correta se a função for chamada diretamente utilizando um ponto `obj.method()` ou a sintaxe de parênteses retos `obj['method']()` (eles fazem o mesmo aqui). Mais adiante neste tutorial, vamos aprender várias formas de resolver este problema, como por exemplo [func.bind()](/bind#solution-2-bind). -## Arrow functions have no "this" +## As funções *arrow* não têm "this" -Arrow functions are special: they don't have their "own" `this`. If we reference `this` from such a function, it's taken from the outer "normal" function. +Funções *arrow* são especiais: elas não possuem o seu "próprio" `this`. Se fizermos referência a `this` dentro de uma tal função, ele é tomado da função externa "normal". -For instance, here `arrow()` uses `this` from the outer `user.sayHi()` method: +Por exemplo, aqui `arrow()` usa o `this` do método externo `user.sayHi()`: ```js run let user = { @@ -336,18 +336,19 @@ let user = { user.sayHi(); // Ilya ``` -That's a special feature of arrow functions, it's useful when we actually do not want to have a separate `this`, but rather to take it from the outer context. Later in the chapter we'll go more deeply into arrow functions. +Essa, é uma particularidade especial das funções *arrow*, e é útil quando na realidade não quisermos ter um `this` em separado, mas apenas o obter do contexto exterior. Mais adiante, no capítulo trataremos com mais pormenor de funções *arrow*. + +## Sumário -## Summary +- Funções que são armazenadas em propriedades de objetos são chamadas de "métodos". +- Métodos permitem a objetos "interagir", como `object.doSomething()`. +- Métodos podem referenciar o objeto por `this`. -- Functions that are stored in object properties are called "methods". -- Methods allow objects to "act" like `object.doSomething()`. -- Methods can reference the object as `this`. +O valor de `this` é definido em tempo-de-execução. -The value of `this` is defined at run-time. -- When a function is declared, it may use `this`, but that `this` has no value until the function is called. -- That function can be copied between objects. -- When a function is called in the "method" syntax: `object.method()`, the value of `this` during the call is `object`. +- Quando uma função é declarada, pode empregar o `this`, mas esse `this` não tem qualquer valor até a função ser chamada. +- Essa função pode ser copiada entre objetos. +- Quando uma função é chamada pela sintaxe de "método" `object.method()`, o valor de `this` durante a chamada é `object`. -Please note that arrow functions are special: they have no `this`. When `this` is accessed inside an arrow function, it is taken from outside. +Por favor, note que funções *arrow* são especiais: elas não possuem `this`. Quando `this` é acedido dentro de uma função *arrow*, o valor é tomado de fora.