Javascript Clases
Javascript Clases
class Foo {}
The fundamental part of most classes is its constructor, which sets up each instance's initial state
and handles any
It's defined in a class block as though you're defining a method named constructor, though it's
actually handled
as a special case.
class MyClass {
constructor(option) {
this.option = option;
Example usage:
const foo = new MyClass('speedy'); // logs: "Creating instance using speedy option"
A small thing to note is that a class constructor cannot be made static via the static keyword, as
described below
Inheritance works just like it does in other object-oriented languages: methods defined on the
superclass are
If the subclass declares its own constructor then it must invoke the parents constructor via super()
before it can
access this.
class SuperClass {
constructor() {
this.logger = console.log;
log() {
this.logger(`Hello ${this.name}`);
constructor() {
super();
this.name = 'subclass';
Static methods and properties are defined on the class/constructor itself, not on instance objects.
These are specified
static myStaticMethod() {
return 'Hello';
return 'Goodbye';
We can see that static properties are not defined on object instances:
Getters and setters allow you to define custom behaviour for reading and writing a given property
on your class. To
the user, they appear the same as any typical property. However, internally a custom function you
provide is used
to determine the value when the property is accessed (the getter), and to preform any necessary
changes when the
In a class definition, a getter is written like a no-argument method prefixed by the get keyword. A
setter is similar,
except that it accepts one argument (the new value being assigned) and the set keyword is used
instead.
Here's an example class which provides a getter and setter for its .name property. Each time it's
assigned, we'll
record the new name in an internal .names_ array. Each time it's accessed, we'll return the latest
name.
class MyClass {
constructor() {
this.names_ = [];
set name(value) {
this.names_.push(value);
get name() {
myClassInstance.name = 'Joe';
myClassInstance.name = 'Bob';
If you only define a setter, attempting to access the property will always return undefined.
set prop(value) {
console.log('setting', value);
};
If you only define a getter, attempting to assign the property will have no effect.
return 5;
};
classInstance.prop = 10;
console.log(classInstance.prop); // logs: 5
JavaScript does not technically support private members as a language feature. Privacy - described
by Douglas
Crockford - gets emulated instead via closures (preserved function scope) that will be generated
each with every
The Queue example demonstrates how, with constructor functions, local state can be preserved
and made
class Queue {
return type;
};
};
}
var q = new Queue; //
//
q.enqueue(8); //
q.enqueue(7); //
//
console.log(q.dequeue()); // 8
console.log(q.dequeue()); // 7
console.log(q); // {}
console.log(Object.keys(q)); // ["enqueue","dequeue"]
Thus both of a Queue type's own methods enqueue and dequeue (see Object.keys(q)) still do have
access to list
that continues to live in its enclosing scope that, at construction time, has been preserved.
Making use of this pattern - emulating private members via privileged public methods - one should
keep in mind
that, with every instance, additional memory will be consumed for every own property method
(for it is code that
can't be shared/reused). The same is true for the amount/size of state that is going to be stored
within such a
closure.
Methods can be defined in classes to perform a function and optionally return a result.
class Something {
constructor(data) {
this.data = data
}
doSomething(text) {
return {
data: this.data,
text
There is also the ability to evaluate expressions when naming methods similar to how you can
access an objects'
properties with []. This can be useful for having dynamic property names, however is often used in
conjunction
with Symbols.
class Car {
constructor(make, model) {
this.make = make;
this.model = model;
[METADATA]() {
return {
make: this.make,
model: this.model
};
// this one is just a string, and could also be defined with simply add()
["add"](a, b) {
return a + b;
[1 + 2]() {
return "three";
MazdaMPV.add(4, 5); // 9
MazdaMPV[3](); // "three"
One of the most common obstacles using classes is finding the proper approach to handle private
states. There are
Using Symbols
A symbol is a unique and immutable data type that may be used as an identifier for object
properties.
const topSecret = Symbol('topSecret'); // our private key; will only be accessible on the scope of
constructor(secret){
};
Because symbols are unique, we must have reference to the original symbol to access the private
property.
But it's not 100% private; let's break that agent down! We can use the
Object.getOwnPropertySymbols method to
Using WeakMaps
WeakMap is a new type of object that have been added for es6.
As defined on MDN
The WeakMap object is a collection of key/value pairs in which the keys are weakly referenced.
The keys must be
The key in a WeakMap is held weakly. What this means is that, if there are no other strong
references to the key,
the entire entry will be removed from the WeakMap by the garbage collector.
The idea is to use the WeakMap, as a static map for the whole class, to hold each instance as key
and keep the
private data as a value for that instance key.
Thus only inside the class will we have access to the WeakMap collection.
const topSecret = new WeakMap(); // will hold all private data of all instances.
constructor(secret){
data
this.doMission = () => {
};
Because the const topSecret is defined inside our module closure, and since we didn't bind it to
our instance
properties, this approach is totally private, and we can't reach the agent topSecret.
The idea here is simply to define all our methods and members inside the constructor and use the
closure to access
constructor(secret){
this.doMission = () => {
};
}
}
In this example as well the data is 100% private and can't be reached outside the class, so our
agent is safe.
We will decide that any property who is private will be prefixed with _.
Note that for this approach the data isn't really private.
constructor(secret){
this.doMission = () => {
figureWhatToDo(this_topSecret);
};
2. The scope of the class itself - within { and } in class {} - const binding
class Foo {
For example,
class A {
foo() {
}
}
function A() {
A = null; // works
A = null; // works
A = null; // works
Clases
Las clases de javascript, introducidas en ECMAScript 2015, son una mejora
sintáctica sobre la herencia basada en prototipos de JavaScript. La sintaxis de las
clases no introduce un nuevo modelo de herencia orientada a objetos en
JavaScript. Las clases de JavaScript proveen una sintaxis mucho más clara y simple
para crear objetos y lidiar con la herencia.
Definiendo clases
Las clases son "funciones especiales", como las expresiones de funciones y declaraciones
de funciones, la sintaxis de una clase tiene dos componentes: expresiones de
clases y declaraciones de clases.
Declaración de clases
Una manera de definir una clase es mediante una declaración de clase. Para declarar una
clase, se utiliza la palabra reservada class y un nombre para la clase "Rectangulo".
class Rectangulo {
constructor(alto, ancho) {
this.alto = alto;
this.ancho = ancho;
}
}
Copy to Clipboard
Alojamiento
class Rectangle {}
Expresiones de clases
Una expresión de clase es otra manera de definir una clase. Las expresiones de clase
pueden ser nombradas o anónimas. El nombre dado a la expresión de clase nombrada es
local dentro del cuerpo de la misma.
// Anonima
let Rectangulo = class {
constructor(alto, ancho) {
this.alto = alto;
this.ancho = ancho;
}
};
console.log(Rectangulo.name);
// output: "Rectangulo"
// Nombrada
let Rectangulo = class Rectangulo2 {
constructor(alto, ancho) {
this.alto = alto;
this.ancho = ancho;
}
};
console.log(Rectangulo.name);
// output: "Rectangulo2"
Nota: Las expresiones de clase están sujetas a las mismas restricciones de elevación que se
describen en la sección Class declarations.
Modo estricto
El cuerpo de las declaraciones de clase y las expresiones de clase son ejecutadas en modo
estricto. En otras palabras, el código escrito aquí está sujeto a una sintaxis más estricta para
aumentar el rendimiento, se arrojarán algunos errores silenciosos y algunas palabras clave
están reservadas para versiones futuras de ECMAScript.
Constructor
El método constructor es un método especial para crear e inicializar un objeto creado con
una clase. Solo puede haber un método especial con el nombre "constructor" en una clase.
Si esta contiene mas de una ocurrencia del método constructor, se arrojará
un Error SyntaxError
Métodos prototipo
class Rectangulo {
constructor (alto, ancho) {
this.alto = alto;
this.ancho = ancho;
}
// Getter
get area() {
return this.calcArea();
}
// Método
calcArea () {
return this.alto * this.ancho;
}
}
console.log(cuadrado.area); // 100
Copy to Clipboard
Métodos estáticos
La palabra clave static define un método estático para una clase. Los métodos estáticos son
llamados sin instanciar su clase y no pueden ser llamados mediante una instancia de clase.
Los métodos estáticos son a menudo usados para crear funciones de utilidad para una
aplicación.
class Punto {
constructor ( x , y ){
this.x = x;
this.y = y;
}
static distancia ( a , b) {
const dx = a.x - b.x;
const dy = a.y - b.y;
return Math.sqrt ( dx * dx + dy * dy );
}
}
Cuando un método estático o método del prototipo es llamado sin un valor para "this" (o
con "this" como booleano, cadena, número, undefined o null), entonces el valor de "this"
será undefined dentro de la funciona llamada. Autoboxing no ocurrirá. El comportamiento
será igual inclusive si se escribe el código en modo no estricto.
class Animal {
hablar() {
return this;
}
static comer() {
return this;
}
}
Si se escribe el código del cuadro superior usando clases función tradicionales, entonces
autoboxing ocurrirara porque tomará valor de "this" sobre la función que es llamada.
function Animal() { }
Animal.prototype.hablar = function(){
return this;
}
Animal.comer = function() {
return this;
}
class Animal {
constructor(nombre) {
this.nombre = nombre;
}
hablar() {
console.log(this.nombre + ' hace un ruido.');
}
}
var Animal = {
hablar() {
console.log(this.nombre + ' hace ruido.');
},
comer() {
console.log(this.nombre + ' se alimenta.');
}
};
class Perro {
constructor(nombre) {
this.nombre = nombre;
}
hablar() {
console.log(this.nombre + ' ladra.');
}
}
Especies
Quizás se quiera devolver objetos Array derivados de la clase array MyArray. El
patron species permite sobreescribir constructores por defecto.
Por ejemplo, cuando se usan metodos del tipo map() que devuelven el constructor por
defecto, se quiere que esos métodos devuelvan un objeto padre Array, en vez de MyArray.
El símbolo Symbol.species permite hacer:
class Gato {
constructor(nombre) {
this.nombre = nombre;
}
hablar() {
console.log(this.nombre + ' hace ruido.');
}
}
Mix-ins
Subclases abstractas or mix-ins son plantillas de clases. Una clase ECMAScript solo puede
tener una clase padre, con lo cual la herencia multiple no es posible. La funcionalidad debe
ser proporcionada por la clase padre.
Una función con una clase padre como entrada y una subclase extendiendo la clase padre
como salida puede ser usado para implementar mix-ins en EMCAScript:
Una clase que use este método puede ser escrita tal que así:
class Foo { }
class Bar extends calculatorMixin(randomizerMixin(Foo)) { }
Copy to Clipboard
Especificaciones
Specification
ECMAScript Language Specification
# sec-class-definitions