JS继承四

来源:互联网 发布:360软件助手不见了 编辑:程序博客网 时间:2024/05/25 21:59
/**
 * @param {String} className
 * @param {String/Function} superClass
 * @param {Function} classImp
 */
function $class(className, superClass, classImp){
    if(superClass === "") superClass = Object;
    var clazz = function(){
        return function(){
            if(typeof this.init == "function"){
                this.init.apply(this, arguments);
            }
        };
    }();
    var p = clazz.prototype = new superClass();
    var _super = superClass.prototype;
    window[className] = clazz;
    classImp.apply(p, [_super]);
}

定义父类Person

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
 * 父类 Person
 */
$class('Person','',function(){
    this.init = function(name){
        this.name = name;
    };
    this.getName = function(){
        return this.name;
    };
    this.setName = function(name){
        this.name = name;
    }
});

子类Man

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
 * 子类 Man
 */
$class('Man', Person, function(supr){
    this.init = function(name, age){
        supr.init.apply(this,[name]);// 该句很重要
        this.age = age;
    };
    this.getAge = function(){
        return this.age;
    };
    this.setAge = function(age){
        this.age = age;
    };
});
var m = new Man('Jack',25);
console.log(m.name);// Jack
console.log(m.age);// 25

从输出看可以看到子类Man的确继承了父类的属性和方法。

原创粉丝点击