Skip to content

Instantly share code, notes, and snippets.

@kameko
Last active November 11, 2018 23:59
Show Gist options
  • Save kameko/26c7b6e2757db8ff7710cf34369a8b10 to your computer and use it in GitHub Desktop.
Save kameko/26c7b6e2757db8ff7710cf34369a8b10 to your computer and use it in GitHub Desktop.
Good way to do OOP in JS
var MyProject = {};
var newobj = function (args) {
return {
public: {},
private: args || {}
};
};
var extendsfrom = function (classname, args) {
return {
public: classname(args),
private: args || {},
base: Object.assign({}, args)
};
}
MyProject.classA = function (args) {
var self = newobj(args);
var public = self.public;
var private = self.private;
public.say_quote = function () {
private.say_name(private.quote);
};
private.say_name = function (str) {
private.say(private.name + " says: " + str);
};
private.say = function (str) {
document.writeln(str);
};
return public;
};
MyProject.classB = function (args) {
var self = extendsfrom(MyProject.classA, args);
var public = self.public;
var private = self.private;
var base = self.base;
public.say_quote = function () {
private.say_name(private.quote + '!');
};
private.say_name = function (str) {
private.say(private.name + " thinks: " + str);
};
private.say = function (str) {
base.say(str);
base.say("also hi");
};
return public;
};
var a1 = MyProject.classA({name: "bill", quote: "eee"});
a1.say_quote();
var a2 = MyProject.classA({name: "abe", quote: "aaaaa"});
a2.say_quote();
var a3 = MyProject.classB({name: "harkinian", quote: "hmm"});
a3.say_quote();
a2.say_quote();
a1.say_quote();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment