Douglas showed a slide showing how he creates JavaScript objects in 2014. He no longer uses Object.create(), avoids 'this' and doesn't even care about memory reduction by using prototypes.
https://www.youtube.com/watch?v=bo36MrBfTk4 (35 mins in)
Here is the pattern described on the slide:
''' function constructor(spec) { var that = otherConstructor(spec), member, method = function () { // spec, member, method }; that.method = method; return that; } '''
Here is my interpretation of this pattern:
function Person(spec) { var person = spec;
// methods
person.getDisplayName = getDisplayName;
return person;
function getDisplayName() {
return person.firstName + " " + person.lastName;
}
}
function Employee(spec) {
var employee = Person(spec);
// members
employee.employeeId = spec.employeeId;
employee.hourlyRate = spec.hourlyRate;
// methods
employee.calculatePay = calculatePay;
return employee;
// implementations
function calculatePay(hoursWorked) {
return employee.hourlyRate * hoursWorked;
}
}
var ben = Employee({ firstName: 'Ben', lastName: 'Priebe', hourlyRate: 120, employeeId: 1 });
console.log(ben.getDisplayName()); console.log(ben.calculatePay(38));
Note to self: Set an object literal as a default spec argument.