-
-
Save chip/8cda61d5b4dc06a1df15 to your computer and use it in GitHub Desktop.
Douglas Crockford - Create Object Recipe (2014)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //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)); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note to self: Set an object literal as a default spec argument.