如果您正在寻找一个简单的轻量级库,它可以准确地为您提供:OOP 在 javascript 中“正确完成”,请查看:https ://github.com/haroldiedema/joii
github页面上的自述文件中提供的源代码示例,以及这些链接:
该库基本上允许您这样定义“类”:
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