Skip to content

Instantly share code, notes, and snippets.

@dwiyatci

dwiyatci/favor-factory.js

Last active Nov 10, 2016
Embed
What would you like to do?
Favoring factory pattern over constructor pattern in JavaScript
//////////// constructor pattern
function Employee() {
this.name = '';
this.salary = 0; // no real encapsulation of private property
}
// too much code noises and bugs-prone from `prototype` and `this`
Employee.prototype.getSalary = function () {
return this.salary;
};
Employee.prototype.setSalary = function (salary) {
if (salary > 0) {
this.salary = salary;
}
};
Employee.prototype.print = function () {
console.log('name: %s, salary: %d', this.name, this.salary);
};
//////////// factory pattern
function EmployeeFactory() {
var salary = 0; // private
var employee = {
name: '', // public
getSalary: getSalary,
setSalary: setSalary,
print: print
};
return employee;
//////////// implementation details
// free yourself from `prototype` and `this` mess which usually becomes the source of bugs ;)
function getSalary() {
return salary;
}
function setSalary(n) {
if (n > 0) {
salary = n;
}
}
function print() {
console.log('name: %s, salary: %d', employee.name, salary);
}
}
//////////// test
var employee = new Employee();
employee.name = 'jaroslaw';
employee.setSalary(5000);
employee.salary = -5000; // oops.. leaking private property :(
employee.print(); // name: jaroslaw, salary: -5000
var employee1 = EmployeeFactory(); // no need to worry about forgetting calling `new`
employee1.name = 'glenn';
employee1.setSalary(1000);
employee1.salary = -1000; // private is safe by closure
employee1.print(); // name: glenn, salary: 1000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.