Skip to content

Instantly share code, notes, and snippets.

@chip
Forked from benpriebe/object-creation.md
Created February 23, 2016 01:56
Show Gist options
  • Select an option

  • Save chip/8cda61d5b4dc06a1df15 to your computer and use it in GitHub Desktop.

Select an option

Save chip/8cda61d5b4dc06a1df15 to your computer and use it in GitHub Desktop.
Douglas Crockford - Create Object Recipe (2014)

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));

@chip
Copy link
Author

chip commented May 31, 2016

Note to self: Set an object literal as a default spec argument.

function Person(spec = {}) {

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment