Por:
Pablo Sanabria
Juan Diego Diaz
Classes vs prototypes
Properties
Static methods
Patterns
Factory
import {Logger} from './classes/logger.js';
class Transport{
constructor(how){
this.logger = new Logger();
this._how = how;
}
move(){
this.logger.log(`Moving in the ${this._how} !!`);
}
get how() {
return this._how;
}
set how(value) {
this._how = how;
}
}
class Drone extends Transport{
constructor(how = 'air' )
{
super(how);
}
}
class Car extends Transport{
constructor(how = 'ground' )
{
super(how);
}
}
class TransportFactory{
static getTransport(transportType){
if(transportType == null)
return null;
else if(transportType === 'car')
return new Car();
else if(transportType=== 'drone')
return new Drone();
else
return null;
}
}
TransportFactory.getTransport('car').move();// Transport class
function Transport(how) {
this.logger = console
this._how = how;
}
Transport.prototype.move = function () {
this.logger.log('Moving in the {0}!!'.replace('{0}', this._how));
};
Object.defineProperty(Transport.prototype, "how", {
get: function () {
return this._how;
},
set: function (value) {
this._how = value;
}
});
// Drone class
function Drone(how) {
how = how || 'air';
Transport.call(this, how);
}
Drone.prototype = Object.create(Transport.prototype);
// Car class
function Car(how) {
how = how || 'ground';
Transport.call(this, how);
}
Car.prototype = Object.create(Transport.prototype);
function TransportFactory() {}
TransportFactory.getTransport = function (transportType) {
if (transportType == null) {
return null;
} else if (transportType === 'car') {
return new Car();
} else if (transportType === 'drone') {
return new Drone();
} else {
return null;
}
}
TransportFactory.getTransport('car').move();
ES6
ECMAScript 5
Más que azúcar sintactico
Las propiedades estáticas se heredan
// ES5
function B() {}
B.f = function () {};
function D() {}
D.prototype = Object.create(B.prototype);
D.f(); // error// ES6
class B {
static f() {}
}
class D extends B {}
D.f(); // okLos constructores de objetos built-in pueden ser heredados
// ES5
function D() {
Array.apply(this, arguments);
}
D.prototype = Object.create(Array.prototype);
var d = new D();
d[0] = 42;
d.length; // 0 - bad, no array exotic behavior// ES6
class D extends Array {}
let d = new D();
d[0] = 42;
d.length; // 1 - good, array exotic behavior