使用Modello编写JavaScript类

2019-06-03 13:29:45王旭

1,定义一个类

Point = Class.create();
/*
  创建一个类。用过 prototype.js 的人觉得很熟悉吧;)
*/

2,注册一个类

Point.register("Modello.Point");
/*
  这里"Modello"是命名空间,"Point"是类名,之间用"."分隔
  如果注册成功,
  Point.namespace 等于 "Modello",Point.classname 等于 "Point"。
  如果失败 Modello 会抛出一个异常,说明失败原因。
*/

Point.register("Point"); // 这里使用默认的命名空间 "std"

Class.register(Point, "Point"); // 使用 Class 的 register 方法

3,获取已注册的类

P = Class.get("Modello.Point");
P = Class.get("Point"); // 这里使用默认的命名空间 "std"

4,使用继承

ZPoint = Class.create(Point); // ZPoint 继承 Point

ZPoint = Class.create("Modello.Point"); // 继承已注册的类

ZPoint = Class.create(Point1, Point2[, ...]);
/*
  多继承。参数中的类也可以用已注册的类名来代替
*/

/*
  继承关系:
  Point.subclasses 内容为 [ ZPoint ]
  ZPoint.superclasses 内容为 [ Point ]
*/

5,定义类的静态成员

Point.count = 0;
Point.add = function(x, y) {
    return x + y;
}

6,定义类的构造函数

Point.construct = function($self, $class) {

    // 用 "var" 来定义私有成员
    var _name = "";
    var _getName = function () {
        return _name;
    }

    // 用 "this" 来定义公有成员
    this.x = 0;
    this.y = 0;
    this.initialize = function (x, y) { // 初始化函数
        this.x = x;
        this.y = y;
        $class.count += 1; // 访问静态成员

    // 公有方法访问私有私有属性
    this.setName = function (name) {
        _name = name;
    }

    this.getName = function () {
        return _getName();