You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: readme.md
+83-81Lines changed: 83 additions & 81 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,6 +1,6 @@
1
-
# Principles of Writing Consistent, Idiomatic JavaScript
1
+
# Princípios para Escrever Javascript de forma Consistente e Idiomática
2
2
3
-
## This is a living document and new ideas for improving the code around us are always welcome. Contribute: fork, clone, branch, commit, push, pull request.
3
+
## Este é um documento vivo e novas idéias para melhorar os códigos correspondentes são sempre bem vindas. Contribua: faça fork, clone, branch, commit, push, pull request.
4
4
5
5
* Rick Waldron [@rwaldron](http://twitter.com/rwaldron), [github](https://github.com/rwldrn)
* Leo Balter [@leobalter](http://twitter.com/leobalter), [github](https://github.com/leobalter)
12
13
13
-
## All code in any code-base should look like a single person typed it, no matter how many people contributed.
14
+
## Todo código em qualquer aplicação deve parecer como se fosse escrito por uma única pessoa, independente de quantas pessoas tenham contribuído.
14
15
15
-
### The following list outlines the practices that I use in all code that I am the original author of; contributions to projects that I have created should follow these guidelines.
16
+
### A lista a seguir descreve as práticas que eu uso em todo código onde sou o autor original; contribuições em projetos que eu criei devem seguir essas mesmas orientações.
16
17
17
-
### I do not intend to impose my style preferences on other people's code; if they have an existing common style - this should be respected.
18
+
### Eu não tenho a intenção de impor minhas preferências por estilos nos códigos de outras pessoas; se eles seguem um estilo em comum - isso deve ser respeitado.
18
19
19
-
> "Part of being a good steward to a successful project is realizing that writing code for yourself is a Bad Idea™. If thousands of people are using your code, then write your code for maximum clarity, not your personal preference of how to get clever within the spec." - Idan Gazit
20
+
> "Parte de ser um bom gestor de um projeto bem sucedido é perceber que escrever código para si mesmo é uma má idéia™. Se milhares de pessoas estão utilizando o seu código, então escreva o seu código com máxima clareza, não sob a sua preferência pessoal sobre como ser esperto com uma especificação." - Idan Gazit
### Qualidade de Código: Ferramentas, Recursos e Referências Bacanas
30
32
31
33
*[jsPerf](http://jsperf.com/)
32
34
*[jsFiddle](http://jsfiddle.net/)
@@ -35,14 +37,14 @@
35
37
*[jshint](http://jshint.com/)
36
38
*[jslint](http://jslint.org/)
37
39
38
-
[Leveraging Code Quality Tools by Anton Kovalyov](http://anton.kovalyov.net/slides/gothamjs/)
40
+
[Leveraging Code Quality Tools (em pt_BR: Aproveitamento de Ferramentas de Qualidade de Código) por Anton Kovalyov](http://anton.kovalyov.net/slides/gothamjs/)
39
41
40
42
41
-
### Get Smart
43
+
### Fique Ligado
42
44
43
45
[http://es5.github.com/](http://es5.github.com/)
44
46
45
-
The following should be considered 1) incomplete, and 2) *REQUIRED READING*. I don't always agree with the style written by the authors below, but one thing is certain: They are consistent. Furthermore, these are authorities on the language.
47
+
Deve ser considerado o seguinte: 1) incompleto; e 2) *LEITURA OBRIGATÓRIA*. Eu não concordo sempre com os estilos escritos pelos autores abaixo, mas uma coisa é certa: Eles são consistentes. Além disso, esses são autoridades na linguagem.
Projects should always attempt to include some generic means by which source can be compressed in preparation for production use. Some popular and proven tools include the JavaScript-based [Uglify.js](https://github.com/mishoo/UglifyJS), as well as the Java-based [Google Closure Compiler](http://code.google.com/closure/compiler/)and[YUI Compressor](http://developer.yahoo.com/yui/compressor/). Choose one and support it.
58
+
Projetos devem sempre tentar incluir alguns formatos genéricos para que o código fonte possa ser compactado no preparo para uso em produção. Algumas ferramentas populares e testadas incluem o [Uglify.js](https://github.com/mishoo/UglifyJS) feito em JavaScript, assim como o [Google Closure Compiler](http://code.google.com/closure/compiler/)e[YUI Compressor](http://developer.yahoo.com/yui/compressor/) feitos em Java. Escolha um e apoie o mesmo.
57
59
58
-
You can now find a functional, generic "build kit" in the `/kits`directory of this repository. Usage is easy: 1) copy the contents of a kit found in `/kits`to a new working directory, 2) save your project .js file in the `/src` directory, 3) put the name of the project in`project.txt`, 4) run `make`from command line. (Even easier directions: replace occurrences of "foo")
60
+
Você pode encontrar um "build kit" funcional e genérico no diretório `/kits`deste repositório. A Utilização é simples: 1) copie o conteúdo de um dos kits encontrados em `/kits`para um novo diretório, 2) grave o arquivo .js de seu projeto no diretório `/src`, 3) coloque o nome do projeto dentro de`project.txt`, 4) execute o `make`pela linha de comando. (Caminho mais fácil: troque as ocorrências de "foo")
59
61
60
62
61
-
### Test Facility
63
+
### Ambiente de Teste
62
64
63
-
Projects _must_ include some form of unit, reference, implementation or functional testing. Use case demos DO NOT QUALIFY as "tests". The following is a list of test frameworks, none of which are endorsed more than the other.
65
+
Projetos _devem_ incluir alguma forma de teste unitário, por referência, de implementaçao ou funcional. Demonstrações de casos de uso NÃO SE QUALIFICAM como "testes". A lista a seguir contém frameworks de testes, nenhuma delas é considerada melhor que as demais.
64
66
65
67
*[QUnit](http://github.com/jquery/qunit)
66
68
*[Jasmine](https://github.com/pivotal/jasmine)
@@ -69,132 +71,132 @@ Projects _must_ include some form of unit, reference, implementation or function
*[Checagem de Escrita (Cortesia das Recomendações de Estilo do Núcleo do jQuery)](#type)
79
+
*[Avaliação Condicional](#cond)
80
+
*[Estilo Prático](#practical)
81
+
*[Nomenclatura](#naming)
82
+
*[Miscelâneas](#misc)
83
+
*[Objetos Nativos e Hospedados](#native)
84
+
*[Comentários](#comments)
83
85
84
86
85
-
## Idiomatic Style Manifesto
87
+
## Manifesto de Estilo Idiomático
86
88
87
89
88
-
1. <aname="whitespace">Whitespace</a>
90
+
1. <aname="whitespace">Espaço em Branco</a>
89
91
90
-
* Never mix spaces and tabs.
91
-
* When beginning a project, before you write any code, choose between soft indents (spaces) or real tabs — this is law.
92
-
* For readability, I always recommend setting your editor's indent size to two characters — this means two spaces or two spaces representing a real tab.
93
-
* If your editor supports it, always work with the "show invisibles" setting turned on. The benefits of this practice are:
94
-
* Enforced consistency
95
-
* Eliminating end of line whitespace
96
-
* Eliminating blank line whitespace
97
-
* Commits and diffs that are easier to read
92
+
* Nunca misture espaços e tabs.
93
+
* Quando começar um projeto, antes de escrever qualquer código, escolha entre indentação suave (espaços) ou tabulação real (tabs) - isso é lei.
94
+
* Pela legibilidade, eu sempre recomendo que configure o tamanho de indentação de seu editor para dois caracteres - isso significa dois espaços ou dois espaços representando um tab real.
95
+
* Se o seu editor suportar, sempre trabalhe com a configuração de "mostrar caracteres invisíveis" ligada. Os benefícios desta prática são:
96
+
* Fortalecer a consistência
97
+
* Eliminação de espaço em branco ao final da linha
98
+
* Eliminação de espaços em uma linha em branco
99
+
* Leituras de commits e diffs ficam mais legíveis
98
100
99
101
100
-
2. <aname="spacing">Beautiful Syntax</a>
102
+
2. <aname="spacing">Sintaxe Bonita</a>
101
103
102
-
A. Parens, Braces, Linebreaks
104
+
A. Parênteses, Chaves e Quebras de Linhas
103
105
104
106
```javascript
105
107
106
-
// if/else/for/while/try always have spaces, braces and span multiple lines
107
-
// this encourages readability
108
+
// if/else/for/while/try sempre tem espaços, chaves e ocorrem em múltiplas linhas
109
+
// isso facilita a legibilidade
108
110
109
111
// 2.A.1.1
110
-
// Examples of really cramped syntax
112
+
// Exemplos de código pouco claro/bagunçado
111
113
112
-
if(condition) doSomething();
114
+
if(condicao) facaAlgo();
113
115
114
-
while(condition) iterating++;
116
+
while(condicao) iteracao++;
115
117
116
-
for(var i=0;i<100;i++) someIterativeFn();
118
+
for(var i=0;i<100;i++) algumaIteracao();
117
119
118
120
119
121
// 2.A.1.1
120
-
// Use whitespace to promote readability
122
+
// Use espaço em branco para facilitar a leitura
121
123
122
-
if ( condition ) {
123
-
// statements
124
+
if ( condicao ) {
125
+
// instruções
124
126
}
125
127
126
-
while ( condition ) {
127
-
// statements
128
+
while ( condicao ) {
129
+
// instruções
128
130
}
129
131
130
132
for ( var i = 0; i < 100; i++ ) {
131
-
// statements
133
+
// instruções
132
134
}
133
135
134
-
// Even better:
136
+
// Ainda melhor:
135
137
136
138
var i,
137
139
length = 100;
138
140
139
141
for ( i = 0; i < length; i++ ) {
140
-
// statements
142
+
// instruções
141
143
}
142
144
143
-
// Or...
145
+
// Ou...
144
146
145
147
var i = 0,
146
148
length = 100;
147
149
148
150
for ( ; i < length; i++ ) {
149
-
// statements
151
+
// instruções
150
152
}
151
153
152
154
var prop;
153
155
154
156
for ( prop in object ) {
155
-
// statements
157
+
// instruções
156
158
}
157
159
158
160
159
161
if ( true ) {
160
-
// statements
162
+
// instruções
161
163
} else {
162
-
// statements
164
+
// instruções
163
165
}
164
166
```
165
167
166
168
167
-
B. Assignments, Declarations, Functions ( Named, Expression, Constructor )
169
+
B. Atribuições, Declarações, Funções ( Nomenclatura, Expressão, Construtor )
168
170
169
171
```javascript
170
172
171
173
// 2.B.1.1
172
-
// Variables
174
+
// Variáveis
173
175
var foo = "bar",
174
176
num = 1,
175
177
undef;
176
178
177
-
// Literal notations:
179
+
// Notações Literais:
178
180
var array = [],
179
181
object = {};
180
182
181
183
182
184
// 2.B.1.2
183
-
// Using only one `var` per scope (function) promotes readability
184
-
// and keeps your declaration list free of clutter (also saves a few keystrokes)
185
-
186
-
// Bad
185
+
// Utilizando apenas um `var` por escopo (função) promove legibilidade
186
+
// e mantém a sua lista de declaração livre de desordem (além de evitar algumas tecladas)
187
+
188
+
// Ruim
187
189
var foo = "";
188
190
var bar = "";
189
191
var qux;
190
192
191
-
// Good
193
+
// Bom
192
194
var foo = "",
193
195
bar = "",
194
196
quux;
195
197
196
-
// or..
197
-
var // Comment on these
198
+
// ou..
199
+
var // comentário aqui
198
200
foo = "",
199
201
bar = "",
200
202
quux;
@@ -204,44 +206,44 @@ Projects _must_ include some form of unit, reference, implementation or function
204
206
```javascript
205
207
206
208
// 2.B.2.1
207
-
// Named Function Declaration
209
+
// Declaração de Função Nomeada
208
210
function foo( arg1, argN ) {
209
211
210
212
}
211
213
212
-
// Usage
214
+
// Utilização
213
215
foo( arg1, argN );
214
216
215
217
216
218
// 2.B.2.2
217
-
// Named Function Declaration
219
+
// Declaração de Função Nomeada
218
220
function square( number ) {
219
221
return number * number;
220
222
}
221
223
222
-
// Usage
224
+
// Utilização
223
225
square( 10 );
224
226
225
-
// Really contrived continuation passing style
227
+
// Estilo de passagem artificialmente contínua
226
228
function square( number, callback ) {
227
229
callback( number * number );
228
230
}
229
231
230
232
square( 10, function( square ) {
231
-
// callback statements
233
+
// instruções de callback
232
234
});
233
235
234
236
235
237
// 2.B.2.3
236
-
// Function Expression
238
+
// Expressão de Função
237
239
var square = function( number ) {
238
-
// Return something valuable and relevant
240
+
// Retorna algo de valor e relevante
239
241
return number * number;
240
242
};
241
243
242
-
// Function Expression with Identifier
243
-
// This preferred form has the added value of being
244
-
// able to call itself and have an identity in stack traces:
244
+
// Expressão de Função com Identificador
245
+
// Esse formato preferencial tem o valor adicional de permitir
246
+
// chamar a si mesmo e ter uma identidade na pilha de comandos:
245
247
var factorial = function factorial( number ) {
246
248
if ( number < 2 ) {
247
249
return 1;
@@ -252,13 +254,13 @@ Projects _must_ include some form of unit, reference, implementation or function
0 commit comments