Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Translated Comments, Polyfills and index#108

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
vplentinax merged 22 commits intojavascript-tutorial:masterfromNiroa95:master
Jun 7, 2020
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
Show all changes
22 commits
Select commitHold shift + click to select a range
770ffb8
Translated "Comments" to Spanish
Niroa95Sep 26, 2019
a4eac2e
Translated Polyfills and index.md to Spanish
Niroa95Oct 1, 2019
4d59710
Translated index.md
Niroa95Oct 1, 2019
d0256b9
Merge branch 'master' into master
joaquinelioJun 4, 2020
1423018
Update article.md
joaquinelioJun 7, 2020
3f24e45
Update article.md
joaquinelioJun 7, 2020
600defa
Update 1-js/03-code-quality/06-polyfills/article.md
vplentinaxJun 7, 2020
ecf907a
Update 1-js/03-code-quality/06-polyfills/article.md
vplentinaxJun 7, 2020
a8338d6
Update 1-js/03-code-quality/03-comments/article.md
vplentinaxJun 7, 2020
82a7ad9
Update 1-js/03-code-quality/03-comments/article.md
vplentinaxJun 7, 2020
4e61df3
Update 1-js/03-code-quality/03-comments/article.md
vplentinaxJun 7, 2020
5748803
Update 1-js/03-code-quality/03-comments/article.md
vplentinaxJun 7, 2020
94502aa
Update 1-js/03-code-quality/03-comments/article.md
vplentinaxJun 7, 2020
121ea66
Update 1-js/03-code-quality/03-comments/article.md
vplentinaxJun 7, 2020
e0991ff
Update 1-js/03-code-quality/03-comments/article.md
vplentinaxJun 7, 2020
b8cb7ad
Update 1-js/03-code-quality/03-comments/article.md
vplentinaxJun 7, 2020
a177987
Update 1-js/03-code-quality/03-comments/article.md
vplentinaxJun 7, 2020
3596a2d
Update 1-js/03-code-quality/03-comments/article.md
vplentinaxJun 7, 2020
b60d1da
Update 1-js/03-code-quality/03-comments/article.md
vplentinaxJun 7, 2020
4705c46
Update 1-js/03-code-quality/03-comments/article.md
vplentinaxJun 7, 2020
3b79f5b
Update 1-js/03-code-quality/03-comments/article.md
vplentinaxJun 7, 2020
a4f4473
Update 1-js/03-code-quality/03-comments/article.md
vplentinaxJun 7, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
169 changes: 84 additions & 85 deletions1-js/03-code-quality/03-comments/article.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,38 @@
#Comments
#Comentarios

As we know from the chapter <info:structure>,comments can be single-line: starting with `//`and multiline: `/* ... */`.
Como hemos aprendido en el capítulo <info:structure>,los comentarios pueden ser de una sola línea: comenzando con `//`y de múltiples líneas: `/* ... */`.

We normally use them to describe how and why the code works.
Normalmente los usamos para describir cómo y por qué el código funciona.

At first sight, commenting might be obvious, but novices in programming often use them wrongly.
A primera vista, los comentarios pueden ser obvios, pero los principiantes en programación generalmente los usan incorrectamente.

##Bad comments
##Comentarios incorrectos

Novices tend to use comments to explain "what is going on in the code".Like this:
Los rincipiantes tienden a utilizar los comentarios para explicar "lo que está pasando en el código".Así:

```js
//This code will do this thing(...)and that thing (...)
// ...and who knows what else...
very;
complex;
code;
//Este código hará esto(...)y esto (...)
// ...y quién sabe qué más...
código;
muy;
complejo;
```

But in good code, the amount of such "explanatory" comments should be minimal. Seriously, the code should be easy to understand without them.
Pero en un buen código, la cantidad de comentarios "explicativos" debería ser mínima. En serio, el código debería ser fácil de entender sin ellos.

There's a great rule about that: "if the code is so unclear that it requires a comment, then maybe it should be rewritten instead".
Existe una fantástica regla al respeto: "si el código es tan poco claro que necesita un comentario, tal vez en su lugar debería ser reescrito.".

###Recipe: factor out functions
###Receta: funciones externas

Sometimes it's beneficial to replace a code piece with a function, like here:
A veces es beneficioso reemplazar trozos de código con funciones, como aquí:

```js
function showPrimes(n) {
nextPrime:
for (let i = 2; i < n; i++) {

*!*
//check if iis a prime number
//comprobar si ies un número primo
for (let j = 2; j < i; j++) {
if (i % j == 0) continue nextPrime;
}
Expand All@@ -43,8 +43,7 @@ function showPrimes(n) {
}
```

The better variant, with a factored out function `isPrime`:

La mejor variante, con una función externa `isPrime`:

```js
function showPrimes(n) {
Expand All@@ -65,21 +64,21 @@ function isPrime(n) {
}
```

Now we can understand the code easily. The function itself becomes the comment. Such code is called *self-descriptive*.
Ahora podemos entender el código fácilmente. La propia función se convierte en comentario. Este tipo de código se le llama *auto descriptivo*.

###Recipe: create functions
###Receta: crear funciones

And if we have a long "code sheet" like this:
Y si tenemos una larga "hoja de código" como esta:

```js
//here we add whiskey
//aquí añadimos whiskey
for(let i = 0; i < 10; i++) {
let drop = getWhiskey();
smell(drop);
add(drop, glass);
}

//here we add juice
//aquí añadimos zumo
for(let t = 0; t < 3; t++) {
let tomato = getTomato();
examine(tomato);
Expand All@@ -90,7 +89,7 @@ for(let t = 0; t < 3; t++) {
// ...
```

Then it might be a better variant to refactor it into functions like:
Entonces, una versión mejor puede ser reescribirlo en funciones de esta manera:

```js
addWhiskey(glass);
Expand All@@ -111,70 +110,70 @@ function addJuice(container) {
}
```

Once again, functions themselves tell what's going on. There's nothing to comment. And also the code structure is better when split. It's clear what every function does, what it takes and what it returns.

In reality, we can't totally avoid "explanatory" comments. There are complex algorithms. And there are smart "tweaks" for purposes of optimization. But generally we should try to keep the code simple and self-descriptive.

## Good comments

So, explanatory comments are usually bad. Which comments are good?

Describe the architecture
: Provide a high-level overview of components, how they interact, what's the control flow in various situations... In short -- the bird's eye view of the code. There's a special language [UML](http://wikipedia.org/wiki/Unified_Modeling_Language) to build high-level architecture diagrams explaining the code. Definitely worth studying.

Document function parameters and usage
: There's a special syntax [JSDoc](http://en.wikipedia.org/wiki/JSDoc) to document a function: usage, parameters, returned value.

For instance:
```js
/**
* Returns x raised to the n-th power.
*
* @param {number} x The number to raise.
* @param {number} n The power, must be a natural number.
* @return {number} x raised to the n-th power.
*/
function pow(x, n) {
...
}
```

Such comments allow us to understand the purpose of the function and use it the right way without looking in its code.
De nuevo, la propias funciones nos dicen qué está pasando. No hay nada que comentar. Y además, la estructura del código es mejor cuando está dividida. Queda claro qué hace cada función, qué necesita y qué retorna.

By the way, many editors like [WebStorm](https://www.jetbrains.com/webstorm/) can understand them as well and use them to provide autocomplete and some automatic code-checking.
En realidad, no podemos evitar totalmente los comentarios "explicativos". Existen algoritmos complejos. Y existen "trucos" ingeniosos con el propósito de optimizar. Pero generalmente, tenemos que intentar mantener el código simple y auto descriptivo.

Also, there are tools like [JSDoc 3](https://github.com/jsdoc3/jsdoc) that can generate HTML-documentation from the comments. You can read more information about JSDoc at <http://usejsdoc.org/>.
## Comentarios correctos

Why is the task solved this way?
: What's written is important. But what's *not* written may be even more important to understand what's going on. Why is the task solved exactly this way? The code gives no answer.
Entonces, los comentarios explicativos suelen ser incorrectos. ¿Qué comentarios son correctos?

If there are many ways to solve the task, why this one? Especially when it's not the most obvious one.
Describe la arquitectura
: Proporcionan una descripción general de alto nivel de los componentes, cómo interactúan, cuál es el flujo de control en diversas situaciones... En resumen -- la vista panorámica del código. Hay un lenguaje de diagramas especial [UML](https://es.wikipedia.org/wiki/Lenguaje_unificado_de_modelado) para diagramas de alto nivel. Definitivamente vale la pena estudiarlo.

Without such comments the following situation is possible:
1. You (or your colleague) open the code written some time ago, and see that it's "suboptimal".
2. You think: "How stupid I was then, and how much smarter I'm now", and rewrite using the "more obvious and correct" variant.
3. ...The urge to rewrite was good. But in the process you see that the "more obvious" solution is actually lacking. You even dimly remember why, because you already tried it long ago. You revert to the correct variant, but the time was wasted.
Documenta la utilización de una función
: Hay una sintaxis especial [JSDoc](https://en.wikipedia.org/wiki/JSDoc) para documentar una función: utilización, parámetros, valor devuelto.

Comments that explain the solution are very important. They help to continue development the right way.

Any subtle features of the code? Where they are used?
: If the code has anything subtle and counter-intuitive, it's definitely worth commenting.

## Summary

An important sign of a good developer is comments: their presence and even their absence.

Good comments allow us to maintain the code well, come back to it after a delay and use it more effectively.

**Comment this:**

- Overall architecture, high-level view.
- Function usage.
- Important solutions, especially when not immediately obvious.

**Avoid comments:**

- That tell "how code works" and "what it does".
- Put them in only if it's impossible to make the code so simple and self-descriptive that it doesn't require them.

Comments are also used for auto-documenting tools like JSDoc3: they read them and generate HTML-docs (or docs in another format).
Por ejemplo:
```js
/**
* Devuelve x elevado a la potencia de n.
*
* @param {number} x El número a elevar.
* @param {number} n La potencia, debe ser un número natural.
* @return {number} x elevado a la potencia de n.
*/
function pow(x, n) {
...
}
```

Estos tipos de comentarios nos permiten entender el propósito de la función y cómo usarla de la manera correcta sin mirar su código.

Por cierto, muchos editores como [WebStorm](https://www.jetbrains.com/webstorm/) también pueden entenderlos y usarlos para proveer auto completado y algún tipo de verificación automática para el código.

Además, existen herramientas como [JSDoc](https://github.com/jsdoc3/jsdoc) que pueden generar documentación en formato HTML de los comentarios. Puedes leer más información sobre JSDoc aquí <http://usejsdoc.org/>.

¿Por qué se resuelve de esa manera?
: Lo que está escrito es importante. Pero lo que *no* está escrito puede ser aún más importante para entender qué está pasando. ¿Por qué resuelven la tarea exactamente de esa manera? El código no nos da ninguna respuesta.

Si hay muchas maneras de resolver el problema, ¿por qué esta? Especialmente cuando no es la más obvia.

Sin dichos comentarios, las siguientes situaciones son posibles:
1. Tú (o tu compañero) abres el código escrito hace ya algún tiempo, y te das cuenta de que es "subóptimo".
2. Piensas: "Que estúpido que era antes, y que inteligente que soy ahora", y lo reescribes utilizando la variante "más obvia y correcta".
3. ...El impulso de reescribir era bueno. Pero en el proceso ves que la solución "más obvia" en realidad falla. Incluso recuerdas vagamente el porqué, porque ya lo intentaste hace mucho. Vuelves a la variante correcta pero has estado perdiendo el tiempo.

Los comentarios que explican la solución correcta son muy importantes. Nos ayudan a continuar el desarrollo de forma correcta.

¿Alguna característica sutil del código? ¿Dónde se usan?
: Si el código tiene algo sutil y contraintuitivo, definitivamente vale la pena comentarlo.

## Resumen

Una señal importante de un buen desarrollador son los comentarios: su presencia e incluso su ausencia.

Los buenos comentarios nos permiten mantener bien el código, volver después de un retraso y usarlo de manera más efectiva.

**Comenta esto:**

- Arquitectura en general, vista de alto nivel.
- Utilización de funciones.
- Soluciones importantes, especialmente cuando no son inmediatamente obvias.

**Evita comentarios:**

- Que explican "cómo funciona el código" y "qué hace".
- Escríbelos solo si es imposible escribir el código de manera tan simple y auto descriptiva que no los necesite.

Los comentarios también son usados para herramientas de auto documentación como JSDoc3: los leen y generan documentación en HTML (o documentos en otros formatos).
46 changes: 22 additions & 24 deletions1-js/03-code-quality/06-polyfills/article.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,54 +1,52 @@

# Polyfills

TheJavaScriptlanguage steadily evolves. New proposals to the language appear regularly, they are analyzed and, if considered worthy, are appended to the list at <https://tc39.github.io/ecma262/>and then progress to the [specification](http://www.ecma-international.org/publications/standards/Ecma-262.htm).
El lenguajeJavaScriptevoluciona constantemente. Nuevas propuestas al lenguaje aparecen regularmente, son analizadas y, si se consideran valiosas, se agregan a la lista en <https://tc39.github.io/ecma262/>y luego avanzan hasta [specification](http://www.ecma-international.org/publications/standards/Ecma-262.htm).

Teams behind JavaScriptengines have their own ideas about what to implement first. They may decide to implement proposals that are in draft and postpone things that are already in the spec, because they are less interesting or just harder to do.
Equipos detrás de intérpretes (engines) de JavaScript tienen sus propias ideas sobre qué implementar primero. Pueden decidir implementar propuestas que están en borrador y posponer cosas que ya están en la especificación, porque son menos interesantes o simplemente más difíciles de hacer.

So it's quite common for an engine to implement only the part of the standard.
Por lo tanto, es bastante común para un intérprete implementar solo la parte del estándar.

A good page to see the current state of support for language features is<https://kangax.github.io/compat-table/es6/> (it's big, we have a lot to study yet).
Una buena página para ver el estado actual de soporte para características del lenguaje es<https://kangax.github.io/compat-table/es6/> (es grande, todavía tenemos mucho que aprender).

## Babel

When we use modern features of the language, some engines may fail to support such code. Just as said, not all features are implemented everywhere.
Cuando usamos características modernas del lenguaje, puede que algunos intérpretes no soporten dicho código. Como hemos dicho, no todas las características están implementadas en todas partes.

Here Babelcomes to the rescue.
Aquí Babelviene al rescate.

[Babel](https://babeljs.io)is a [transpiler](https://en.wikipedia.org/wiki/Source-to-source_compiler).It rewrites modernJavaScriptcode into the previous standard.
[Babel](https://babeljs.io)es un [transpiler](https://en.wikipedia.org/wiki/Source-to-source_compiler).Reescribe códigoJavaScriptmoderno en el estándar anterior.

Actually, there are two parts in Babel:
En realidad, hay dos partes en Babel:

1.First, the transpiler program, which rewrites the code. The developer runs it on their own computer. It rewrites the code into the older standard. And then the code is delivered to the website for users. Modern project build systems like[webpack](http://webpack.github.io/)provide means to runtranspilerautomatically on every code change, so that it's very easy to integrate into development process.
1.Primero, el programa transpiler, que reescribe código. El desarrollador lo ejecuta en su propio ordenador. Reescribe el código al viejo estándar. Y entonces el código es entregado al navegador para los usuarios. Proyectos modernos para construcción de sistemas como[webpack](http://webpack.github.io/)o [brunch](http://brunch.io/), proporcionan medios para ejecutar eltranspilerautomáticamente en cada cambio al código, de modo que no implique ninguna perdida de tiempo de nuestra parte.

2.Second, the polyfill.
2.Segundo, el polyfill.

New language features may include new built-in functions and syntax constructs.
The transpiler rewrites the code, transforming syntax constructs into older ones. But as for new built-in functions, we need to implement them. JavaScript is a highly dynamic language, scripts may add/modify any functions, so that they behave according to the modern standard.
El transpiler reescribe el código, por lo que se cubren las características de la sintaxis. Pero para funciones nuevas tenemos que escribir un script especial que las implemente. JavaScript es un lenguaje muy dinámico, puede que los scripts no solo agreguen nuevas funciones, sino también modifiquen las funciones incorporadas, para que actúen de forma correspondiente al estándar moderno.

A script that updates/adds new functions is called "polyfill". It "fills in" the gap and adds missing implementations.
Existe el término "polyfill" para scripts que "llenan"(fill in) el vacío y agregan las implementaciones que faltan.

Two interestingpolyfillsare:
- [core js](https://github.com/zloirock/core-js) that supports a lot, allows to include only needed features.
- [polyfill.io](http://polyfill.io)service that provides a script withpolyfills, depending on the features and user's browser.
Dospolyfillsinteresantes son:
- [babel polyfill](https://babeljs.io/docs/usage/polyfill/) que soporta mucho, pero es muy grande.
- [polyfill.io](http://polyfill.io)servicio que nos permite cargar/construirpolyfills bajo demanda, dependiendo de las características que necesitemos.

So, if we're going to use modern language features, a transpilerand apolyfillare necessary.
Así que, si queremos usar características modernas del lenguaje, el transpilerypolyfillson necesarios.

##Examples in the tutorial
##Ejemplos en el tutorial


````online
Most examples are runnable at-place, like this:
La mayoría de ejemplos se pueden ejecutar en el sitio, así:

```js run
alert('Press the"Play"button in the upper-right corner to run');
alert('Presione el botón"Play"en la esquina superior derecha para ejecutar');
```

Examples that use modernJSwill work only if your browser supports it.
Ejemplos que usanJSmoderno solo funcionarán si tu navegador lo soporta.
````

```offline
As you're reading the offline version, in PDFexamples are not runnable. In EPUBsome of them can run.
Como estás leyendo la verión offline, en PDFlos ejemplos no se pueden ejecutar. En EPUBalgunos pueden ejecutarse.
```

Google Chromeis usually the most up-to-date with language features, good to run bleeding-edge demoswithout any transpilers, but other modern browsers also work fine.
Generalmente,Google Chromeestá actualizado con las últimas características del lenguaje, funciona bien para ejecutar demoscon tecnología puntera sin ningún transpiler, pero otros navegadores modernos también funcionan bien.
4 changes: 2 additions & 2 deletions1-js/03-code-quality/index.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
#Code quality
#Calidad del c�digo

This chapter explains coding practices that we'll use further in the development.
Este capitulo explica practicas en programaci�n que usaremos durante el desarrollo.
6 changes: 3 additions & 3 deletions1-js/index.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
#The JavaScript language
#El lenguaje JavaScript

Here we learnJavaScript,starting from scratch and go on to advanced concepts likeOOP.
Aqu� aprendemosJavaScript,empezando desde zero y pasando a conceptos avanzados comoOOP (programaci�n orientada a objetos).

We concentrate on the language itself here, with the minimum of environment-specific notes.
Aqu� nos concentramos en el lenguaje en si mismo, con el m�nimo de notas espec�ficas del entorno.


[8]ページ先頭

©2009-2025 Movatter.jp