javascript class vs factory function code example
Example 1: javascript constructor function vs factory function
function ConstructorFunction() {
this.someProp1 = "1";
this.someProp2 = "2";
}
ConstructorFunction.prototype.someMethod = function() { };
function factoryFunction() {
var obj = {
someProp1 : "1",
someProp2 : "2",
someMethod: function() { }
};
return obj;
}
Example 2: factory function vs constructor javascript
function ConstructorCar () {}
ConstructorCar.prototype.drive = function () {
console.log('Vroom!');
};
const car2 = new ConstructorCar();
console.log(car2.drive());
const proto = {
drive () {
console.log('Vroom!');
}
};
const factoryCar = () => Object.create(proto);
const car3 = factoryCar();
console.log(car3.drive());
class ClassCar {
drive () {
console.log('Vroom!');
}
}
const car1 = new ClassCar();
console.log(car1.drive());