javascript 写的一个类的demo

来源:luqidong 发布时间:2014-03-03 15:58:42 点击数:
var Class = function (parent) {
    var klass = function () {
        this.init.apply(this, arguments);
    };
    klass.prototype.init = function () {
    };
    //定义类的别名
    klass.fn = klass.prototype;
    //判断是否是集成
    if (parent) {
        var subclass = function () {
        };
        subclass.prototype = parent.prototype;
        klass.prototype = new subclass;
    }
    //包装函数确保他们在正确的作用于被调用
    klass.proxy = function (func) {
        var self = this;
        return(function () {
            return func.apply(self, arguments);
        });
    }
    klass.fn.proxy = klass.proxy;


    klass.fn.parent = klass;
    klass._super = klass.__proto__;
    //给类添加属性
    klass.extend = function (obj) {
        var extended = obj.extended;
        for (var i in obj) {
            klass[i] = obj[i];
        }
        if (extended) extended(klass);
    };

    //给实例添加属性
    klass.include = function (obj) {
        var included = obj.included;
        for (var i in obj) {
            klass.fn[i] = obj[i]
        }
        if (included) included(klass)
    }
    return klass;
}

demo:

var Animal = new Class;

Animal.include({
    breath:function(){
        console.log('breath');
    }
});
var Cat =new Class(Animal)
var tommy = new Cat;
tommy.breath()

78OA办公系统

先创建了一个Animal类,然后里面有breath方法,在创建一个Cat的类继承了Animal,最后实例化一个tommy的毛,里面也有breath方法。

本文由免费oa系统78oa原创,转载请注明出处。