每日一库:JS.Class

介绍:https://github.com/RubyLouvre/JS.Class

<!doctype html>
<html>
<head>
<meta charset="gb2312" />
<title>测试</title>
<script>

var JS = {
  VERSION: '2.2.1'
};

JS.Class = function(classDefinition) {

    //返回目标类的真正构造器
    function getClassBase() {
        return function() {
            //它在里面执行用户传入的构造器construct

            //preventJSBaseConstructorCall是为了防止在createClassDefinition辅助方法中执行父类的construct
            if (typeof this['construct'] === 'function' && preventJSBaseConstructorCall === false) {
                this.construct.apply(this, arguments); //this 实例
            }
        };
    }

    //为目标类添加类成员与原型成员
    function createClassDefinition(classDefinition) {
        //此对象用于保存父类的同名方法
        var parent = this.prototype["parent"] || (this.prototype["parent"] = {});

        for (var prop in classDefinition) {
            if (prop === 'statics') {
                for (var sprop in classDefinition.statics) {
                    this[sprop] = classDefinition.statics[sprop];
                }
            } else {
                //为目标类添加原型成员,如果是函数,那么检测它还没有同名的超类方法,如果有
                if (typeof this.prototype[prop] === 'function') {
                    var parentMethod = this.prototype[prop];
                    parent[prop] = parentMethod;
                }
                this.prototype[prop] = classDefinition[prop];
            }
        }
    }

    var preventJSBaseConstructorCall = true;
    var Base = getClassBase();
    preventJSBaseConstructorCall = false;

    createClassDefinition.call(Base, classDefinition);

    //用于创建当前类的子类
    Base.extend = function(classDefinition) {

        preventJSBaseConstructorCall = true;
        var SonClass = getClassBase();
        SonClass.prototype = new this();//将一个父类的实例当作子类的原型
        preventJSBaseConstructorCall = false;

        createClassDefinition.call(SonClass, classDefinition);
        SonClass.extend = this.extend;

        return SonClass;
    };

    return Base;
};


var Animal = JS.Class({
    construct: function(name) {
        this.name = name;
    },
    shout: function(s) {
        console.log(s);
    }
});

//var animal = new Animal();
//animal.shout('animal'); // animal

var Dog = Animal.extend({
    construct: function(name, age) {
        //调用父类构造器
        this.parent.construct.apply(this, arguments);
        this.age = age;
    },
    run: function(s) {
        console.log(s);
    }
});

var dog = new Dog("dog", 4);
console.log(dog.name);
dog.shout("dog"); // dog
dog.run("run"); // run
console.log(dog.constructor + "")

var Shepherd = Dog.extend({
    statics: {//静态成员
        TYPE: "Shepherd"
    },
    run: function() {//方法链,调用超类同名方法
        this.parent.run.call(this, "fast");
    }
});

console.log(Shepherd.TYPE);//Shepherd
var shepherd = new Shepherd("shepherd", 5);
shepherd.run();//fast

var a = new Animal("xx");
console.log(a.run);
</script>
</head>

<body>

</body>
</html>

  

 

posted @ 2013-02-19 13:58  zhuzefu  阅读(319)  评论(0编辑  收藏  举报