Last active
October 24, 2019 12:30
-
-
Save stonehippo/fec74610ab459c21e260 to your computer and use it in GitHub Desktop.
Douglas Crockford's preferred Javascript object constructor pattern, from https://www.youtube.com/watch?v=bo36MrBfTk4 (starting at 35:45)
This file contains 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
// The pattern Crockford uses these days. | |
function constructor(spec) { | |
var that = other_constructor(spec), | |
member, | |
method = function () { | |
// spec, member, method | |
} | |
that.method = method; | |
return that; | |
} |
This file contains 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
// An implementation of the pattern that I wrote to understand how to use it | |
function constructor(spec) { | |
var that = spec, | |
member = 1.0, | |
method = function () { | |
console.log(["This is spec = ", spec].join("")); | |
console.log(["This is member = ", spec.member].join("")); | |
}; | |
that.method = method; | |
return that; | |
} | |
var module = constructor({member: 2.0, toString: function() {return "My groovy spec object";}}); | |
module.method(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment