Skip to content

Instantly share code, notes, and snippets.

@liweiz
Forked from benpriebe/object-creation.md
Created January 7, 2017 20:25
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 liweiz/09ee31fe2e762c3c5aea3988130c3b2e to your computer and use it in GitHub Desktop.
Save liweiz/09ee31fe2e762c3c5aea3988130c3b2e to your computer and use it in GitHub Desktop.
Douglas Crockford - Create Object Recipe (2014)

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));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment