これを正確に提供するシンプルで軽量なライブラリを探している場合:JavaScriptで「正しく行われた」OOP、これを見てください:https ://github.com/haroldiedema/joii
githubページのreadmeで提供されているソースコードの例と、次のリンク:
このライブラリでは、基本的に「クラス」を次のように定義できます。
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());
// Bob Smith is Developer
編集
コードを例として取り上げますが、JOII互換のコードに変換すると、次のようになります。
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(); // hi!
o.newfoo(); // hi #3
または、ミックスインとして使用します。
var o = new obj_name();
o.mixin(obj_name2);
o.newfoo(); // hi #3
またはその逆で、「特性」を使用します。
// 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 #3