Skip to content

Instantly share code, notes, and snippets.

@dwiyatci
Last active November 10, 2016 12:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dwiyatci/e7c5bc7b1452af5864795de627707f5f to your computer and use it in GitHub Desktop.
Save dwiyatci/e7c5bc7b1452af5864795de627707f5f to your computer and use it in GitHub Desktop.
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