-
-
Save liweiz/3cdd15abc35b9fe4c4d27e02c2ed831a to your computer and use it in GitHub Desktop.
classless javascript
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
// 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