wheregroup / joii
JavaScript 对象继承实现
Requires
This package is auto-updated.
Last update: 2019-09-19 11:32:38 UTC
README
什么是 JOII?
JOII(JavaScript Object Inheritance Implementation 的缩写)将 基于类的编程 带到 JavaScript 中,而不使用编译器。所有操作都使用原生的 JavaScript 完成。JOII 允许您像在大多数其他面向对象的语言中一样使用类和接口来构建应用程序。JOII 旨在与市场上任何 浏览器 兼容。因此,JOII 支持 IE 5.5 及以上版本。
特性
- 支持 Internet Explorer 5.5 及以上版本
- 构建 和 扩展 类
- 支持 接口
- 类属性中的强 类型提示
- 类型提示 用于自定义对象定义
- 可见性设置(公共、受保护)
- Final & abstract 属性和方法
- 特性 / 混入
- 枚举
- 反射
- (自 3.1.0 版起) 自定义构造函数和可调用方法名称
许可证
像大多数其他流行的 JavaScript 库一样,JOII 在 MIT 许可证 下发布。
MIT 许可证简单易懂,对 JOII 项目的使用几乎没有限制。您可以在任何其他项目中(即使是商业项目)使用任何 JOII 项目,只要保留版权头信息。本网站上所有的示例代码都是公有领域,这意味着您可以根据自己的意愿自由使用它们。
安装
浏览器
像加载任何其他库一样加载 JOII。JOII 不需要任何依赖项。
<script src="/path/to/joii.min.js"></script>
JOII 作为 bower 包提供:
bower install joii
Node
使用 npm 安装,如果您想的话,可以自动将 --save
添加到您的 package.json 文件中。
npm install joii --save
在您的 node 项目中某处
// JOII registers itself in the global namespace once loaded. require("joii"); var MyClass = Class({ /* ... /* });
运行单元测试
- 从这里克隆仓库。
- 通过 npm 使用
npm install
安装依赖项 - 使用
npm test
命令运行测试套件 - 可选地,在浏览器中打开
testsuite.html
来查看单元测试的浏览器版本。
预览
这是JOII在实际中运行的一个示例。
// Define a simple class called "Person". var Person = Class({ // Declare a property called 'name'. 'public immutable string name' : null, // Declare a constructor to be executed upon instantiation. 'private construct': function (name) { this.name = name; } }); // Define a class called "Employee" that extends on "Person" var Employee = Class({ extends: Person }, { // Add an 'occupation' property. 'public nullable string occupation' : null, // Override the constructor from "Person". 'private construct' : function (name, occupation) { // invoke the parent constructor this.super('construct', name); // Set the given occupation. this.setOccupation(occupation); } }); var bob = new Employee('Bob'); bob.setOccupation('Developer'); console.log(bob.getName()); // Bob console.log(bob.getOccupation()); // Developer
如您所见,示例代码使用了我们没有定义的setter和getter方法。当一个属性被声明为public时,JOII会自动为该属性生成getter和setter,并在其中执行类型检查。
即使声明为公开,属性也不会暴露给公众。
// properties are never exposed to the public, this is undefined: bob.occupation; // This will throw an exception, because occupation must be a string: bob.setOccupation(123);
当一个属性被声明为protected时,会生成getter和setter,但不会暴露给公众。当一个属性被声明为private时,不会生成任何内容。
更多关于getter和setter的信息请参阅getter和setter部分。
自定义构造方法
从3.1.0版本开始,可以添加自定义构造方法。为了确保与其他基于JOII的库的完全兼容性,构造方法名称只会添加,而不会替换。当找到构造方法时,在实例化过程中不会执行更多的这些方法。
您可以使用JOII.Config.addConstructor('hello');
添加自定义构造方法名称。
例如
// Add the 'hello' constructor. JOII.Config.addConstructor('hello'); var Hi = Class({ hello: function () { console.log('Hello World!'); } }); // Outputs: "Hello World!" new Hi();
请注意,原始/现有构造函数优先,这意味着它们会先执行。
var Hi = Class({ hello: function () { // I am never executed. console.log('Hello World!'); } // __construct is the 'original' constructor, so it gets more priority over the // newly added one, 'hello'. __construct: function () { console.log('Hi there.'); } });