代码改变世界

记录下李战的甘露模型

2010-05-25 14:18  BlueDream  阅读(600)  评论(0编辑  收藏  举报

一年前读过.当一年后再读.发现以前自己根本没有理解.在此记录下代码.以便翻阅.

var object = {
    isA: function(aType) {
        var self = this;
        while (self) {
            if (self == aType) {
                return true;
            } 
            self = self.Type;
        };
        return false;
    }    
};

function Class(aBaseClass, aClassDefine) {
    function class_() {
        this.Type = aBaseClass;
        for (var member in aClassDefine) {
            this[member] = aClassDefine[member];
        } 
    };
    class_.prototype = aBaseClass;
    return new class_()
};

function New(aClass, aParams) {
    function new_() {
        this.Type = aClass;
        if (aClass.Create) 
            aClass.Create.apply(this, aParams);
    };
    new_.prototype = aClass;
    return new new_();
};

var Person = Class(object, {
    Create: function(name, age) {
        this.name = name;
        this.age = age;
    },
    SayHello: function() {
        alert('Hello, I am ' + this.name + ', ' + this.age);
    }
});

var Employee = Class(Person, {
    Create: function(name, age, salary) {
        Person.Create.call(this, name, age);
        this.salary = salary;
    },
    ShowMeTheMoney: function() {
        alert(this.name + ' $ ' + this.salary);
    }
});

var BillGates = New(Person, ['Bill Gates', 53]);
var SteveJobs = New(Employee, ['Steve Jobs', 53, 1234]);
BillGates.SayHello();
SteveJobs.SayHello();
SteveJobs.ShowMeTheMoney();

var LittleBill = New(BillGates.Type, ['Little Bill'], 6);
LittleBill.SayHello();

alert(BillGates.isA(Person));
alert(BillGates.isA(Employee));
alert(SteveJobs.isA(Person));
alert(Person.isA(Employee));
alert(Employee.isA(Person));