Clases y objetos
Ya sabes hacer un objeto con {}. Una clase es el molde para hacer muchos objetos iguales, sin copiar y pegar.
Classes and objects
You already know how to make an object with {}. A class is the mould for making many identical objects, without copy-pasting.
Imagina un juego con varios enemigos. Con lo que ya sabes, harías esto:
Imagine a game with several enemies. With what you already know, you would do this:
Funciona, pero con 20 enemigos serían 20 variables sueltas, y la
función recibirDaño vive separada del objeto al que le hace algo. Una
clase junta los datos y las acciones en un solo molde.
It works, but with 20 enemies that is 20 loose variables, and the
recibirDaño function lives separately from the object it acts on. A
class bundles the data and the actions into one mould.
class define el molde. El constructor es una función especial
que se ejecuta al crear cada objeto nuevo, para darle sus datos iniciales.
this significa "el objeto que se está creando ahora mismo".
class defines the mould. The constructor is a special function
that runs when each new object is created, to give it its starting data.
this means "the object being created right now".
Una función escrita dentro de la clase es un método. En vez de una función suelta que recibe el objeto como argumento, el objeto mismo sabe hacer la acción.
A function written inside the class is a method. Instead of a loose function that takes the object as an argument, the object itself knows how to do the action.
Compara enemigo1.recibirDaño(30) con la versión
anterior, recibirDaño(enemigo1, 30): dicen lo mismo, pero ahora se lee como una
orden que le das al objeto, no una función que opera sobre él desde afuera.
Compare enemigo1.recibirDaño(30) with the earlier
version, recibirDaño(enemigo1, 30): they say the same thing, but now it reads as
an order you give the object, not a function operating on it from outside.
Con extends, una clase hereda todo lo de otra y solo agrega o cambia lo
distinto. super(...) llama al constructor de la clase de la que hereda.
With extends, a class inherits everything from another and only adds or
changes what is different. super(...) calls the parent class's constructor.
class, constructor, this, métodos, y herencia con
extends y super. Todo lo que ya usabas con objetos sueltos, ahora
con un molde reutilizable detrás.
Con esto tienes otra forma de organizar programas más grandes. Pero antes de crecer más, falta algo importante: qué hacer cuando algo sale mal.
class, constructor, this, methods, and inheritance
with extends and super. Everything you already did with loose
objects, now with a reusable mould behind it.
With this you have another way to organise bigger programs. But before growing further, one important thing is missing: what to do when something goes wrong.