Douglas Crockford 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 (skip ahead to 35 mins for relevant section)
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));
There is a problem with using a capital first letter for function names, because jslint requires those constructor functions to be used with the new keyword.
If using lowercase for the function name, such as:
You then have a problem where the person variable cannot be correctly used inside of the function as the spec.
I've asked about this on the JSLint discussion group too at https://plus.google.com/+PaulWilkinsNZ/posts/AP5K1kh55KG