Skip to content

Instantly share code, notes, and snippets.

@stonehippo
Last active October 24, 2019 12:30
Show Gist options
  • Save stonehippo/fec74610ab459c21e260 to your computer and use it in GitHub Desktop.
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)
// 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;
}
// 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