- Notifications
You must be signed in to change notification settings - Fork111
F.prototype#231
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Merged
jonnathan-ls merged 11 commits intojavascript-tutorial:masterfromflaviohblima:develop-function-prototypeSep 18, 2023
Uh oh!
There was an error while loading.Please reload this page.
Merged
F.prototype#231
Changes fromall commits
Commits
Show all changes
11 commits Select commitHold shift + click to select a range
2f6340c
FEAT: Translate F.prototype article, task and solution to pt.
flaviohblima6ed9576
FIX: article/tasks reviews resolved. Translate missing task.
flaviohblima75ce566
FIX: Resolving reviews.
flaviohblima74f456d
Update 1-js/08-prototypes/02-function-prototype/4-new-object-same-con…
flaviohblimafa0c64e
Update 1-js/08-prototypes/02-function-prototype/4-new-object-same-con…
flaviohblima4d86e7c
Update 1-js/08-prototypes/02-function-prototype/4-new-object-same-con…
flaviohblima525cc2e
Update 1-js/08-prototypes/02-function-prototype/4-new-object-same-con…
flaviohblima2157dd4
Update 1-js/08-prototypes/02-function-prototype/article.md
flaviohblima7054535
Update 1-js/08-prototypes/02-function-prototype/article.md
flaviohblimae159873
refactor: applies the corrections requested in the second review of t…
jonnathan-ls2e32549
refactor: translates pending texts in svg files
jonnathan-lsFile filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
12 changes: 6 additions & 6 deletions1-js/08-prototypes/02-function-prototype/1-changing-prototype/solution.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,20 +1,20 @@ | ||
Respostas: | ||
1. `true`. | ||
A atribuição a `Rabbit.prototype`configura o `[[Prototype]]`para novos objetos, mas não afeta os objetos que já existem. | ||
2. `false`. | ||
Objetos são atribuídos por referência. O objeto do `Rabbit.prototype`não é duplicado, ele continua sendo um único objeto referenciado por `Rabbit.prototype`e pelo`[[Prototype]]`do `rabbit`. | ||
Portanto, quando nós mudamos o seu conteúdo através de uma referência, ele fica visível para as outras. | ||
3. `true`. | ||
Todas as operações de`delete`são aplicadas diretamente ao objeto. Neste caso,`delete rabbit.eats`tenta remover a propriedade`eats`do`rabbit`,mas ele não a tem. Assim, essa operação não tem nenhum efeito. | ||
4. `undefined`. | ||
A propriedade `eats`é deletada do protótipo, então ela realmente não existe mais. |
15 changes: 7 additions & 8 deletions1-js/08-prototypes/02-function-prototype/1-changing-prototype/task.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -2,11 +2,11 @@ importance: 5 | ||
--- | ||
#Mudando o "prototype" | ||
No código abaixo, nós criamos um `new Rabbit`,depois tentamos modificar seu protótipo. | ||
No começo, nós temos esse código: | ||
```js run | ||
function Rabbit() {} | ||
@@ -19,8 +19,7 @@ let rabbit = new Rabbit(); | ||
alert( rabbit.eats ); // true | ||
``` | ||
1. Nós adicionamos uma linha (realçada). O que o `alert` vai mostrar agora? | ||
```js | ||
function Rabbit() {} | ||
@@ -37,7 +36,7 @@ alert( rabbit.eats ); // true | ||
alert( rabbit.eats ); // ? | ||
``` | ||
2. ...E se o código for assim (a linha foi substituída)? | ||
```js | ||
function Rabbit() {} | ||
@@ -54,7 +53,7 @@ alert( rabbit.eats ); // true | ||
alert( rabbit.eats ); // ? | ||
``` | ||
3.E se for assim (a linha foi substituída)? | ||
jonnathan-ls marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
```js | ||
function Rabbit() {} | ||
@@ -71,7 +70,7 @@ alert( rabbit.eats ); // true | ||
alert( rabbit.eats ); // ? | ||
``` | ||
4.A última variação: | ||
```js | ||
function Rabbit() {} | ||
30 changes: 15 additions & 15 deletions1-js/08-prototypes/02-function-prototype/4-new-object-same-constructor/solution.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
8 changes: 4 additions & 4 deletions1-js/08-prototypes/02-function-prototype/4-new-object-same-constructor/task.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
96 changes: 48 additions & 48 deletions1-js/08-prototypes/02-function-prototype/article.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,18 +1,18 @@ | ||
# F.prototype | ||
Lembre-se, novos objetos podem ser criados com uma função construtora, usando `new F()`. | ||
Se `F.prototype`for um objeto, então o operador`new`usa ela para configurar o `[[Prototype]]`do novo objeto. | ||
```smart | ||
JavaScripttem herança prototipada desde o começo. Isso era uma das funcionalidades centrais da linguagem. | ||
Mas antigamente não havia um acesso direto a ela. A única coisa que funcionava de forma confiável era uma propriedade `"prototype"`da função construtora, descrita nesse capítulo. Então, existem muitosscriptsque ainda a utilizam. | ||
``` | ||
Note que o `F.prototype`aqui significa uma propriedaderegularchamada`"prototype"`dentro de`F`.Isso soa um poucosimilarao termo"prototype" (protótipo), mas aqui nós estamos falando realmente de uma propriedade regular com esse nome. | ||
Aqui temos um exemplo: | ||
```js run | ||
let animal = { | ||
@@ -27,32 +27,32 @@ function Rabbit(name) { | ||
Rabbit.prototype = animal; | ||
*/!* | ||
let rabbit = new Rabbit("Coelho Branco"); // rabbit.__proto__ == animal | ||
alert( rabbit.eats ); // true | ||
odsantos marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
``` | ||
Configurando `Rabbit.prototype = animal`literalmente significa o seguinte: "Quando o `new Rabbit`for criado, atribua seu `[[Prototype]]`para `animal`". | ||
Essa é a imagem do resultado: | ||
 | ||
Na imagem, `"prototype"`é aseta na horizontal, indicando uma propriedade regular, e `[[Prototype]]`está navertical,indicando a herança de `rabbit`vinda de `animal`. | ||
```smart header="`F.prototype`é usada apenas na chamada`new F`" | ||
A propriedade`F.prototype`é usada apenas quando`new F`é chamado, e ela atribui um valor para o`[[Prototype]]`do novo objeto. | ||
Se, depois da criação, a propriedade`F.prototype`mudar(`F.prototype = <another object>`),então novos objetos criados com `new F`vão ter outro objeto como `[[Prototype]]`,enquanto os objetos que já existirem vão manter o antigo. | ||
``` | ||
## F.prototype padrão, propriedade do construtor | ||
Toda função tem a propriedade`"prototype"`, mesmo quando nós não a provermos. | ||
O`"prototype"`padrão é um objeto com apenas uma propriedade`constructor`que aponta para a própria função a que pertence. | ||
Assim: | ||
```js | ||
function Rabbit() {} | ||
@@ -64,58 +64,58 @@ Rabbit.prototype = { constructor: Rabbit }; | ||
 | ||
Nós podemos conferir isso: | ||
```js run | ||
function Rabbit() {} | ||
//Por definição: | ||
// Rabbit.prototype = { constructor: Rabbit } | ||
alert( Rabbit.prototype.constructor == Rabbit ); // true | ||
``` | ||
Naturalmente, se nós não fizermos nada, a propriedade`constructor`está disponível para todos os coelhos (*rabbits*) através do `[[Prototype]]`: | ||
```js run | ||
function Rabbit() {} | ||
//Por definição: | ||
// Rabbit.prototype = { constructor: Rabbit } | ||
let rabbit = new Rabbit(); //herda de {constructor: Rabbit} | ||
alert(rabbit.constructor == Rabbit); // true (vindo do protótipo) | ||
``` | ||
 | ||
Nós podemos usar a propriedade`constructor`para criar um objeto novo usando o próprio construtor de um objeto que já exista. | ||
Como abaixo: | ||
```js run | ||
function Rabbit(name) { | ||
this.name = name; | ||
alert(name); | ||
} | ||
let rabbit = new Rabbit("Coelho Branco"); | ||
*!* | ||
let rabbit2 = new rabbit.constructor("Coelho Preto"); | ||
*/!* | ||
odsantos marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
``` | ||
Isso é prático quando nós temos um objeto, não sabemos que construtor foi usado para ele (de uma biblioteca de terceiros, por exemplo),e nós precisamos de criar outro objeto do mesmo tipo. | ||
Mas provavelmente a coisa mais importante sobre o`"constructor"`é que... | ||
**...O próprioJavaScriptnão garante qual é o valor correto do`"constructor"`.** | ||
Sim, existe um`"prototype"`padrão para funções, mas é só isso. O que acontece com ele depois--está totalmente por nossa conta. | ||
Em particular,se nós substituirmos o `prototype` padrão, não vai haver um`"constructor"`nele. | ||
Por exemplo: | ||
```js run | ||
function Rabbit() {} | ||
@@ -129,18 +129,18 @@ alert(rabbit.constructor === Rabbit); // false | ||
*/!* | ||
``` | ||
Portanto, para manter o`"constructor"`certo, nós podemos escolher adicionar/remover propriedades do`"prototype"`ao invés de sobrescrevê-lo completamente: | ||
```js | ||
function Rabbit() {} | ||
//não sobrescreva Rabbit.prototypecompletamente | ||
//apenas adicione | ||
Rabbit.prototype.jumps = true | ||
//oRabbit.prototype.constructorpadrão fica preservado | ||
``` | ||
Outra alternativa é recriar a propriedade`constructor`manualmente: | ||
```js | ||
Rabbit.prototype = { | ||
@@ -150,26 +150,26 @@ Rabbit.prototype = { | ||
*/!* | ||
}; | ||
//agora oconstructortambém está correto, porque nós o adicionamos | ||
``` | ||
## Resumo | ||
Neste capítulo, nós descrevemos brevemente a forma de configurar um `[[Prototype]]` para os objetos criados via função construtura. Mais tarde nós vamos ver padrões (*patterns*) mais avançados de programação que dependem disso. | ||
É tudo bem simples, mas aqui estão algumas notas para deixar as coisas claras: | ||
- A propriedade `F.prototype` (não confunda com o `[[Prototype]]`) configura o `[[Prototype]]` de novos objetos quando `new F()` é chamado. | ||
- O valor de `F.prototype` deveria ser um objeto ou `null`: outros valores não vão funcionar. | ||
- A propriedade `"prototype"` só tem o efeito especial quando configurada em uma função construtora, e invocada com `new`. | ||
Em objetos regulares, o `prototype` não tem nada de especial: | ||
```js | ||
let user = { | ||
name: "John", | ||
prototype: "Bla-bla" //nenhuma mágica aqui | ||
}; | ||
``` | ||
Por padrão, todas as funções possuem`F.prototype = { constructor: F }`,então nós podemos obter o construtor de um objeto acessando sua propriedade `"constructor"`. |
4 changes: 4 additions & 0 deletionsimages.yml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
proto-constructor-animal-rabbit.svg: | ||
White Rabbit: | ||
text: Coelho Branco | ||
position: center |
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.