Skip to content

Instantly share code, notes, and snippets.

@liweiz
Forked from chip/constructor.js
Created January 7, 2017 20:35
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/3cdd15abc35b9fe4c4d27e02c2ed831a to your computer and use it in GitHub Desktop.
Save liweiz/3cdd15abc35b9fe4c4d27e02c2ed831a to your computer and use it in GitHub Desktop.
classless javascript
// http://stackoverflow.com/questions/27595749/douglas-crockford-on-class-free-oop-in-javascript
// https://www.youtube.com/watch?v=PSGEjv3Tqo0#t=1395
//
// Per Douglas Crockford (but requries ES6 support)
// function constructor(spec) {
// let {member} = spec,
// {other} = other_constructor(spec),
// method = function () {
// // accesses member, other, method, spec
// };
//
// return Object.freeze({
// method,
// other
// });
// }
// Revised version, but using a specific cat "class" example
// instead of an abstract example.
function cat(spec) {
// assign the object specification
var member = spec;
// I'm not using inheritence, so I'm skipping the other_constructor
//{other} = other_constructor(spec),
shout = function() {
// accesses member, other, method, spec
//return member;
return member.name.toUpperCase() + " is a really " +
member.weight + " kitty";
};
// freeze the object to ensure it isn't tampered with
return Object.freeze({
// Must reference shout as the key to reference after instantiation
// The value is the function that is to be made public
shout: shout
});
}
// No need to capitalize class name because it's not really a class
// and we're not using the 'new' keyword.
var garfield = cat({name: 'garfield', weight: 'fat'});
console.log("garfield.shout() ", garfield.shout());
// Also, consider using a namespace for your app
var ChipsApp = {};
ChipsApp.garfield = cat({name: 'garfield', weight: 'fat'});
ChipsApp.garfield.shout();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment