If you are looking for a simple lightweight library that gives you exactly that: OOP is “done right” in javascript, look at this: https://github.com/haroldiedema/joii
The source code examples provided in readme on the github page, as well as these links:
This library basically allows you to define “classes” as such:
var Person = Class(function() { this.firstname = "John" this.surname = "Smith" this.role= "Developer" this.getInfo = function() { return this.firstname + ' ' + this.surname + ' is ' + this.role; }; }); var AnotherPerson = Class({ extends: Person }, function() { this.firstname = "Bob"; }); var p = new AnotherPerson(); console.log(p.getInfo());
Edit
To take your code as an example, but converted to a JOII-compatible code, it would look something like this:
var obj_name = Class(function() { this.foo = function() { alert('hi!'); }; this.foo2 = function() { alert('hi again!'); }; }; var obj_name2 = Class({ extends: obj_name }, function() { this.newfoo = function() { alert('hi #3'); }; }); var o = new obj_name2(); o.foo();
Or use it as a mix:
var o = new obj_name(); o.mixin(obj_name2); o.newfoo();
Or vice versa, using a "sign".
// the "uses" option basically copies content from the given object to the scope of your "class", solving the horizontal code-reuse problem. var obj_name = Class({ uses: [obj_name2], function() { this.foo = function() { alert('hi!'); }; this.foo2 = function() { alert('hi again!'); }; }); var o = new obj_name(); o.newfoo(); // hi
source share