javascript类式继承函数最优版

直接上代码:

klass函数

var klass = function (Parent, props) {
    var Child, F, i;

    //1.新构造函数
    Child = function () {
        if (Child.uber && Child.uber.hasOwnProperty("__construct")) {
            Child.uber.__construct.apply(this, arguments);
        }
        if (Child.prototype.hasOwnProperty("__construct")) {
            Child.prototype.__construct.apply(this, arguments);
        }
    };

    //2.继承
    Parent = Parent || Object;
    F = function () {};
    F.prototype = Parent.prototype;
    Child.prototype = new F();
    Child.uber = Parent.prototype;
    Child.prototype.constructor = Child;

    //3.添加实现方法
    for (i in props) {
        if (props.hasOwnProperty(i)) {
            Child.prototype[i] = props[i];
        }
    }

    //返回该class
    return Child;
};

使用实例:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>类式继承</title>
    <script src="klass.js"></script>
</head>
<body>
<script>
var Man = klass(null, {
    __construct : function (name) {
        console.log("Man's constructor!");
        this.name = name;
    },
    getName : function () {
        return this.name;
    }
});

//var first = new Man('Adam');
//console.log(first.getName());

var SuperMan = klass(Man, {
    __construct : function (name) {
        console.log("SuperMan's constructor!");
    },
    getName : function () {
        var name = SuperMan.uber.getName.apply(this);
        return "I am " + name;
    }
});

var clark = new SuperMan('Clark Kent');
console.log(clark.getName());

</script>
</body>
</html>

 

posted @ 2013-10-16 22:56  breezefeng  阅读(350)  评论(0编辑  收藏  举报